SQl Server Pivot Query(简单分组?)

时间:2016-02-11 23:20:14

标签: sql sql-server sql-server-2008

如何在SQL Server中对以下结果集进行透视:

Source      Type    Count   Sum
--------------------------------------
Apple       FALSE   67      153981
Egg         FALSE   115     75821
Egg         TRUE    832     112773
Jam         FALSE   81      71758
Jam         TRUE    648     85784
Other       FALSE   1228    521206
Other       TRUE    2       282
Pineapple   FALSE   521     1292074
Pineapple   TRUE    698     146585
Watermelon  FALSE   1146    1815607
Watermelon  TRUE    4157    761837

我的最终结果应该是这样的。如果我正确的话,我认为这不可能由简单的小组完成吗?

Source      TRUE    FALSE   Sum
--------------------------------------
Apple       0       67      153981
Egg         832     115     188594
Jam         648     81      157542
Other       2       1228    521488
Pineapple   698     521     1438659
Watermelon  1146    4175    2577444

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

SELECT
    [Source],
    [True]  = SUM(CASE WHEN [Type] = 'TRUE' THEN [Count] ELSE 0 END),
    [False] = SUM(CASE WHEN [Type] = 'FALSE' THEN [Count] ELSE 0 END),
    [Sum]   = SUM([Sum])
FROM tbl
GROUP BY [Source]

作为旁注,您应避免使用COUNTSUM等保留字作为列名。

答案 1 :(得分:0)

可能是使用PIVOT

来回答相同结果集的另一种方法
DECLARE @Table1 TABLE 
    (Source varchar(10), Type varchar(5), Count int, Sum int)
;

INSERT INTO @Table1
    (Source, Type, Count, Sum)
VALUES
    ('Apple', 'FALSE', 67, 153981),
    ('Egg', 'FALSE', 115, 75821),
    ('Egg', 'TRUE', 832, 112773),
    ('Jam', 'FALSE', 81, 71758),
    ('Jam', 'TRUE', 648, 85784),
    ('Other', 'FALSE', 1228, 521206),
    ('Other', 'TRUE', 2, 282),
    ('Pineapple', 'FALSE', 521, 1292074),
    ('Pineapple', 'TRUE', 698, 146585),
    ('Watermelon', 'FALSE', 1146, 1815607),
    ('Watermelon', 'TRUE', 4157, 761837)
;
Select  Source,
        ISNULL(MAX([TRUE]),0)[TRUE],
        ISNULL(MAX([FALSE]),0)[FALSE],
        ISNULL(MAX(SUM),0)SUM 
FROM (
Select Source,Sum,[TRUE],[FALSE]    
    from (
select Source, Sum,Count,Type 
    from @Table1)T
PIVOT (MAX(Count) FOR   
        Type IN([TRUE],[FALSE]) )P)TT
GROUP BY TT.Source