用于计算相同类型元素的SUM的正确SQL查询

时间:2017-05-04 08:22:57

标签: sql

我有一个分发表,如下所示。

ItemKey     DayId    Phase  Usage
300029892   20080702    4   2.323
300029892   20080702    5   2.828
300029892   20080702    6   2.275
300029892   20080702    4   2.312
300029892   20080702    5   2.87
300029892   20080702    6   2.35
300029892   20080702    4   2.238
300029892   20080702    5   2.757
300029892   20080702    6   2.298
300029892   20080702    4   2.262
300029892   20080702    5   2.75
300029892   20080702    6   2.382
300029892   20080702    4   2.273
300029892   20080702    5   2.825
300029892   20080702    6   2.2
300029892   20080702    4   2.34
300029892   20080702    5   2.91
300029892   20080702    6   2.328
300029892   20080702    4   2.26
300029892   20080702    5   2.748
300029892   20080702    6   2.617
300029892   20080702    4   2.27
300029892   20080702    5   2.752
300029892   20080702    6   2.36
300029892   20080702    4   2.287
300029892   20080702    5   2.945
300029892   20080702    6   2.313

现在我希望输出为

ItemKey,  UsageInPhase4,                      UsageInPhase5,  UsageInPhase6
300029892 Sum values in phase 4 over all days Similarly Ph 5  Similarly Ph 6

什么是正确的查询?这是我到目前为止所得到的,但它仍然不是我想要的确切输出。

select Itemkey, DayId, PHase, 
SUM(kwh_Del) over (partition by ItemKey) as TotalKwh,
SUM(kwh_Del) over (partition by PhaseKey)
from [dw].[Distribution]  FER
where FER.ItemKey = 300029892
and dayid = 20080702

2 个答案:

答案 0 :(得分:2)

类似于以下内容的数据透视查询应该有效:

SELECT
    ItemKey,
    DayId,
    SUM(CASE WHEN Phase = 4 THEN Usage ELSE 0 END) AS [UsageOverPhase4],
    SUM(CASE WHEN Phase = 5 THEN Usage ELSE 0 END) AS [UsageOverPhase5],
    SUM(CASE WHEN Phase = 6 THEN Usage ELSE 0 END) AS [UsageOverPhase6]
FROM [dw].[Distribution]
WHERE ItemKey = 300029892 AND
      DayId = 20080702
GROUP BY ItemKey,
         DayId

答案 1 :(得分:1)

如果你有不同数量的阶段,你可以使用这样的动态查询:

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
    SELECT
    ItemKey,
    DayId ' + STUFF(
    (SELECT ', SUM(CASE WHEN Phase = '+CAST(d.Phase AS VARCHAR(3))+' THEN Usage ELSE 0 END) AS [UsageOverPhase'+CAST(d.Phase AS VARCHAR(3))+']'
    FROM (SELECT DISTINCT Phase FROM [dw].[Distribution]) d)
    , 1, 0, '') + '
FROM [dw].[Distribution]
GROUP BY ItemKey,
         DayId'
Exec(@SQL)

这只是@TimBiegeleisen答案的动态修改。