SQL SERVER-找出哪个字段不同

时间:2018-11-26 13:02:45

标签: sql-server field except

我从下面的餐桌水果中有2条记录。我正在使用EXCEPT语句进行比较-请注意,ID字段将被忽略:

ID  Fruit    AmountToday
1    Apple     10
2    Apple     20

我的SQL如下:

SELECT FRUIT,AMOUNTTODAY FROM FRUITS WHERE ID='1'
EXCEPT
SELECT FRUIT,AMOUNTTODAY FROM FRUITS WHERE ID='2'

当前返回整个记录-但我想打印不同的字段名称-即AMOUNTTODAY。

有人知道如何实现吗?

1 个答案:

答案 0 :(得分:0)

这是一个Case语句,用于询问您感兴趣的字段:
这将使用表中的第一条记录与其余记录进行比较。它计算[Fruit]和[AmountToday]之间的差异。

With t As
(
SELECT  
  Case When Fruit <> (Select Top 1 Fruit From Fruits) Then 1 Else 0 End As FruitDiff,
  Case When AmountToday <> (Select Top 1 AmountToday From Fruits) Then 1 Else 0 End As AmtDiff
FROM FRUITS 
)
Select 
Sum(FruitDiff) As FruitDiffs,
Sum(AmtDiff) As AmtDiffs
From t

结果:

FruitDiffs  AmtDiffs

0             1