我有一张有很多列的桌子。有时我需要找到两行之间的差异。我只需滚动屏幕就可以做到这一点,但它很乏味。我正在寻找一个可以为我执行此操作的查询,例如
SELECT columns_for_id_1 != columns_for_id_2
FROM xyz
WHERE id in (1,2)
表:
id col1 col2 col3 col4
1 qqq www eee rrr
2 qqq www XXX rrr
结果:
"Different columns: id, col3"
有没有简单的方法可以做到这一点?
更新
另一个想要的例子: 我拥有的(表有超过 50 列,而不仅仅是 7 列):
Id| Col1 | Col2 | Col3 | Col4 | Col5 | Col6 |
==============================================
1 | aaa | bbb | ccc | ddd | eee | fff |
----------------------------------------------
2 | aaa | XXX | ccc | YYY | eee | fff |
查询:
SELECT *
FROM table
WHERE Id = 1 OR Id = 2
AND "columns value differs"
查询结果:
"Id, Col2, Col4"
或者类似的东西:
Id|Col2 |Col4 |
===============
1 |bbb |ddd |
---------------
2 |XXX |YYY |
现在我必须滚动超过 50 列来查看行是否相同,效率不高且容易出错。我不想像这样的长查询
SELECT (COMPARE Id1.Col1 with Id2.Col1 if different then print "Col1 differs", COMPARE Id1.Col2 with Id2.Col2...)
因为我自己会更快地比较行;)
类似这样的:
SELECT col, MIN(VAL) AS val1, MAX(val) AS val2
FROM (
SELECT id, val, col
FROM (
SELECT id, [col1], [col2], [col3], [col4]
FROM mytable
WHERE id IN (1,2)) AS src
UNPIVOT (
val FOR col IN ([col1], [col2], [col3], [col4])) AS unpvt ) AS t
GROUP BY col
HAVING MIN(val) <> MAX(val)
输出:
col val1 val2
================
col3 eee XXX
尝试这个简单的查询,可能会对您有帮助
SELECT (CASE WHEN a.col1 <> b.col1 THEN 'Different Col1'
WHEN a.col2 <> b.col2 THEN 'Different Col2'
...
ELSE 'No Different' END) --You can add only required columns here
FROM xyz AS a
INNER JOIN xyz AS b ON b.id = 1 --First Record
WHERE a.id = 2 --Second record to compare
如果您使用的是 SQL Server 2012,那么您还可以使用 LEAD/LAG 窗口功能来执行此操作。 MSDN 参考在这里 - https://msdn.microsoft.com/en-us/library/hh213125.aspx
select
id,
col1,
col2,
col3,
col4,
stuff(diff_cols,len(diff_cols-1),1,'') diff_cols
from
(
SELECT
id,
col1,
col2,
col3,
col4,
concat
(
'Different columns:',
CASE
WHEN LEAD(id, 1,0) OVER (ORDER BY id) <> id THEN 'id,'
WHEN LEAD(col1, 1,0) OVER (ORDER BY id) <> col1 THEN 'col1,'
WHEN LEAD(col2, 1,0) OVER (ORDER BY id) <> col2 THEN 'col2,'
WHEN LEAD(col3, 1,0) OVER (ORDER BY id) <> col3 THEN 'col3,'
WHEN LEAD(col4, 1,0) OVER (ORDER BY id) <> col4 THEN 'col4,'
) diff_cols
FROM xyz
) tmp
我喜欢Giorgos Betsos回答的优雅,但它给了我一个“缺少右括号”错误(?),这就是为什么我重构它以使其工作并且对我来说更具可读性。请随意摆弄我的工作示例here或here。
create table a_table
(
id int,
col1 varchar(255),
col2 varchar(255),
col3 varchar(255),
col4 varchar(255)
);
insert into a_table values
(1,'aaa','bbb','ZZZ', 'ddd'),
(2,'aaa','XXX','ccc', 'YYY'),
(3,'UUU','bbb','VVV', 'ddd');
WITH orig_data_query AS
(
SELECT id, col1, col2, col3, col4
FROM a_table
WHERE id IN (1,2)
),
pivot_query AS
(
SELECT id, val, col
FROM orig_data_query
UNPIVOT
(
val FOR col IN (col1, col2, col3, col4)
)
)
SELECT col, MIN(VAL) AS val1, MAX(val) AS val2
FROM pivot_query
GROUP BY col
HAVING MIN(val) <> MAX(val);