我有要求,我需要比较单个表的两行,并选择具有不同值的列。
主键是姓名和状态。
示例数据:
Row1: 'Jack', 1, a, b, c, d, e, f
Row2: 'Jack', 2, a, b, x, d, y, f
所以我的要求是选择x和y。 这里'杰克'是姓名,1,2是状态。
答案 0 :(得分:0)
If the Columns are same
SELECT a.col1,a.Col2 FROM (SELECT col1,Col2 FROM Table WHERE id=1 UNION SELECT col1,Col2 FROM Table WHERE id=2) a
另外我们也可以这样做
select t1.value,t2.value
from Table t1
inner join Table t2 on
t1.id = t2.id
答案 1 :(得分:0)
我认为应该是这样的:
SELECT T1.*
FROM MainTable AS T1
INNER JOIN MainTable AS T2
ON T1.Name = T2.Name
AND T1.Status != T2.Status
AND (T1.col1 != T2.col1
OR T1.col2 != T2.col2
OR T1.col3 != T2.col3)
您可以选择名称匹配且状态不匹配的匹配项,以及至少有一列不匹配的匹配项。
根据要求更新: 如果您只想要列,那么最可读的是为每列创建单独的选择:
SELECT T2.col1
FROM MainTable AS T1
INNER JOIN MainTable AS T2
ON T1.Name = T2.Name
AND T1.Status != T2.Status
AND T1.col1 != T2.col1
UNION ALL
SELECT T2.col2
FROM MainTable AS T1
INNER JOIN MainTable AS T2
ON T1.Name = T2.Name
AND T1.Status != T2.Status
AND T1.col2 != T2.col2
UNION ALL
SELECT T2.col3
FROM MainTable AS T1
INNER JOIN MainTable AS T2
ON T1.Name = T2.Name
AND T1.Status != T2.Status
AND T1.col3 != T2.col3
And so on....