比较一个表中的总和

时间:2013-05-30 05:42:15

标签: sql sql-server-2008

我有一张桌子:

System | Pcs | Article
----------------------
s1     | 1   | a1
s2     | 1   | a1
...................
s1     | 5   | a2
s2     | 2   | a2
s2     | 3   | a2
...................
s1     | 8   | a3
s2     | 1   | a3
s2     | 2   | a3
s2     | 3   | a3

并且需要在不同系统中对SUM篇文章进行比较并相互比较,因此结果应如下所示:

System | SUM(Pcs) | Article | Check
------------------------------------
s1     | 1        | a1      | OK
s2     | 1        | a1      | OK
s1     | 5        | a2      | OK
s2     | 5        | a2      | OK
s1     | 8        | a3      | Not OK
s2     | 6        | a3      | Not OK

Check专栏告诉我们,不同系统中同一篇文章的总和相等。

理解清楚吗?我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

使用此查询,每个文章的系统数量是否未知数无关紧要。

WITH records
AS
(
    SELECT  Article, System, SUM(pcs) Pcs
    FROM    tableName
    GROUP   BY Article, System
),
records2
AS
(
    SELECT  Article, 
            COUNT(DISTINCT pcs) totalCount
    FROM    records
    GROUP   BY Article
)
SELECT  a.System, a.Pcs, a.Article,
        CASE WHEN b.totalCount = 1 THEN 'OK' ELSE 'NOT OK' END AS [Check]
FROM    records a
        INNER JOIN records2 b
            ON a.Article = b.Article

输出

╔════════╦═════╦═════════╦════════╗
║ SYSTEM ║ PCS ║ ARTICLE ║ CHECK  ║
╠════════╬═════╬═════════╬════════╣
║ s1     ║   1 ║ a1      ║ OK     ║
║ s2     ║   1 ║ a1      ║ OK     ║
║ s1     ║   5 ║ a2      ║ OK     ║
║ s2     ║   5 ║ a2      ║ OK     ║
║ s1     ║   8 ║ a3      ║ NOT OK ║
║ s2     ║   6 ║ a3      ║ NOT OK ║
╚════════╩═════╩═════════╩════════╝

答案 1 :(得分:1)

请查找以下查询将帮助您

SELECT 
    [System], 
    SumOfPcs, 
    Article,
    CASE WHEN SumOfPcs = OtherArticleSum THEN 'OK' ELSE 'NOT OK' END AS [Check]
FROM 
(
    SELECT 
        [System],
        sum(Pcs) as SumOfPcs,
        Article,
        (SELECT 
                SUM(demoin.Pcs)
            FROM demo demoin
            WHERE NOT (demoin.[System] = demoout.[System] AND demoin.Article = demoout.Article) 
                AND demoin.Article = demoout.Article
        ) AS OtherArticleSum

    FROM demo demoout
    GROUP BY [System], Article
) tbl