我在 sql server 上有一组数据,例如:
ID ID_Invoice Article Quantity Status
1 10 carrot 10 null
2 10 carrot 5 C
3 10 onion 8 null
4 10 onion 4 C
5 11 tomato 20 null
6 11 tomato 18 C
7 11 onion 2 null
8 11 onion 1 C
这意味着客户订购了 10 个胡萝卜和 8 个洋葱(在一张发票上),但实际上只收到了 5 个胡萝卜和 4 个洋葱。如果状态为空则为原始数量,如果状态为C则为更正数量
我需要生成一个表
ID ID_Invoice Article Quantity
1 10 carrot -5
2 10 onion -4
3 11 tomato -2
4 11 onion -1
它显示了每张发票上订购数量和实际数量之间的差异。我不知道如何开始。任何帮助深表感谢:)
最佳答案
带有简单 CASE 表达式的选项,没有过多的 JOIN
SELECT ID_Invoice, Article,
SUM(CASE WHEN Status IS NULL
THEN -1 * Quantity ELSE Quantity END) AS Quantity
FROM dbo.test38
GROUP BY ID_Invoice, Article
结果:
ID_Invoice Article Quantity
10 carrot -5
10 onion -4
11 onion -1
11 tomato -2
SQLFiddle 上的演示
关于sql - 找出两组记录之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430451/