示例:我需要其中id = 1的金额之和不等于id<>的金额之和的数字。 1,连同id和差异。
表(在本例中为视图)可能如下所示:
NUMBER AMOUNT ID
0001 500 1
0001 500 2
0002 400 3
0003 299 1
0003 300 3
0003 300 3
非常感谢你对此的帮助。
答案 0 :(得分:0)
使用此查询,您可以获得按编号分组的金额总和,ID等于1且ID不等于1.
SELECT NUMBER
, SUM(CASE WHEN ID = 1 THEN AMOUNT ELSE 0 END) AS Equals1
, SUM(CASE WHEN ID <> 1 THEN AMOUNT ELSE 0 END) AS NotEquals1
FROM DataTable
GROUP BY NUMBER
如果这是您所期望的,请使用以下查询来获取按编号分组的差异金额。
SELECT NUMBER, (Equals1 - NotEquals1) AS DifferenceAmount
FROM
(
SELECT NUMBER
, SUM(CASE WHEN ID = 1 THEN AMOUNT ELSE 0 END) AS Equals1
, SUM(CASE WHEN ID <> 1 THEN AMOUNT ELSE 0 END) AS NotEquals1
FROM DataTable
GROUP BY NUMBER
) AS GroupedTable
WHERE Equals1 <> NotEquals1
答案 1 :(得分:0)
SELECT
MyView.Number,
MyView.Amount - D.OverOneTotal AS Difference
FROM
MyView
LEFT JOIN
(SELECT
Number,
SUM(Amount) OverOneTotal
FROM
MyView
WHERE
ID > 1
GROUP BY
Number) D ON MyView.Number = D.Number
WHERE
MyView.ID = 1
AND MyView.Amount <> D.OverOneTotal