1

我有一张桌子:

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专栏告诉我们,同一篇文章在不同系统中的总和是相等的。

是否清楚明白?我怎样才能做到这一点?

4

2 回答 2

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 ║
╚════════╩═════╩═════════╩════════╝
于 2013-05-30T05:51:41.087 回答
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
于 2013-05-30T06:09:12.197 回答