0

示例:我需要其中 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

非常感谢您对此的帮助。

4

2 回答 2

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 
于 2012-10-16T11:45:27.433 回答
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
于 2012-10-16T11:39:24.617 回答