SQL Server组按结果集创建2个单独的行而不是1个组合行

时间:2016-06-24 12:27:00

标签: sql sql-server sql-server-2008 tsql group-by

以下是我当前表格的一个示例:

ProjectID   Level       Cost
---------   ---------   ---------  
101         LVL_1       1000.00
101         LVL_2       2500.00
102         LVL_1       1500.00
102         LVL_2       3000.00
103         LVL_2       1200.00

当我运行以下查询时:

SELECT 
    ProjectID,
    CASE WHEN Level = 'LVL_1'
         THEN Cost
         END AS Level1,
    CASE WHEN Level = 'LVL_2'
         THEN Cost
         END AS Level2,
    SUM(Cost) 
FROM 
    Table
GROUP BY 
    Level,
    ProjectID

我得到的结果集如下:

ProjectID   Level1      Level2      TotalCost
---------   ---------   ---------   ---------
101         1000.00     NULL        3500.00
101         NULL        2500.00     3500.00
102         1500.00     NULL        4500.00
102         NULL        3000.00     4500.00
103         NULL        1200.00     1200.00

然而,我需要的是这种布局:

ProjectID   Level1      Level2      TotalCost
---------   ---------   ---------   ---------
101         1000.00     2500.00     3500.00
102         1500.00     3000.00     4500.00
103         NULL        1200.00     1200.00

我意识到问题是Group by,因为我不想按级别分组,我只想按ProjectID本身进行分组。 但是我不知道如何解决这个问题,因为我正在使用SUM函数,任何帮助将不胜感激。 提前谢谢!

另外请注意,我的查询比这更复杂。这是一个简化版本。

4 个答案:

答案 0 :(得分:4)

SELECT 
    ProjectID,
    SUM(CASE WHEN Level = 'LVL_1'
         THEN Cost ELSE 0
         END) AS Level1,
    SUM(CASE WHEN Level = 'LVL_2'
         THEN Cost ELSE 0
         END) AS Level2,
    SUM(Cost) 
FROM 
    Table
GROUP BY 

    ProjectID

答案 1 :(得分:1)

试试这个,

SELECT 
    ProjectID,
    SUM(CASE WHEN Level = 'LVL_1'
         THEN Cost
         END) AS Level1,
    SUM(CASE WHEN Level = 'LVL_2'
         THEN Cost
         END) AS Level2,
    SUM(Cost) 
FROM 
    Table
GROUP BY 
    ProjectID

答案 2 :(得分:1)

试试这个

SELECT 
        [ProjectID]
    ,   SUM(CASE WHEN [Level] = 'LVL_1' THEN [TotalCost] END) as [Level1]
    ,   SUM(CASE WHEN [Level] = 'LVL_2' THEN [TotalCost] END) as [Level2]
    ,   SUM([TotalCost]) as TotalCost
FROM (

    SELECT 
            [ProjectID]
        ,   [Level]
        ,   SUM([Cost]) as TotalCost
    FROM 
        [Table]
    GROUP BY
            [ProjectID]
        ,   [Level]

    ) t
GROUP BY
        t.[ProjectID]

答案 3 :(得分:0)

试试这个,希望这可以帮助你...

   SELECT 
        ProjectID,
        max(CASE WHEN Level = 'LVL_1'
             THEN Cost
             END) AS Level1,
        max(CASE WHEN Level = 'LVL_2'
             THEN Cost
             END) AS Level2,
        SUM(Cost) 
    FROM 
        Table
    GROUP BY 
        ProjectID