WITH ROLLUP在Select中要求SUM?

时间:2016-12-07 14:17:12

标签: sql tsql rollup

没有人能够帮我解决原始问题(WITH ROLLUP is only producing NULLs

此后我发现了解决方案的PART。我将查询减少到以下内容。

SELECT
    wlc.WorkloadCategory
    ,wl.WorkloadMinutes
FROM
    swam.WorkloadCategories  wlc
INNER JOIN  
    swam.Workloads wl 
        ON wlc.WorkloadCategoryID = wl.WorkloadCategoryID
WHERE 
    wlc.WorkloadCategory = 'DI'
GROUP BY
    wlc.WorkloadCategory
    ,wl.WorkloadMinutes WITH ROLLUP

我得到了以下结果:

WorkloadCategory    |   WorkloadMinutes
--------------------|------------------
DI                  |   31
DI                  |   55
DI                  |   77
DI                  |   79
DI                  |   98
DI                  |   117
DI                  |   NULL
NULL                |   NULL

但我期待(457是总数,而NULL 457是总数):

WorkloadCategory    |   WorkloadMinutes
--------------------|------------------
DI                  |   31
DI                  |   55
DI                  |   77
DI                  |   79
DI                  |   98
DI                  |   117
DI                  |   457
NULL                |   457

一位同事建议进行以下更改(添加SUM)。除了第5行(196而不是98,使值加倍),它完成所有操作,现在总数为555而不是457。

SELECT
    wlc.WorkloadCategory
    ,SUM(wl.WorkloadMinutes) as WorkloadMinutes
FROM
    swam.WorkloadCategories  wlc
INNER JOIN  
    swam.Workloads wl 
        ON wlc.WorkloadCategoryID = wl.WorkloadCategoryID
WHERE 
    wlc.WorkloadCategory = 'DI'
GROUP BY
    wlc.WorkloadCategory
    ,wl.WorkloadMinutes WITH ROLLUP

结果:

WorkloadCategory    |   WorkloadMinutes
--------------------|------------------
DI                  |   31
DI                  |   55
DI                  |   77
DI                  |   79
DI                  |   196
DI                  |   117
DI                  |   555
NULL                |   555

任何人都可以解释为什么SUM会部分提供我想要的东西,但是然后错误地选择了一行的WorkloadMinutes?非常感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

正如马丁史密斯指出的那样,

"推测底层结果集有两行98"

......这就是我讨厌继承项目的原因。