按汇总和计数分组(不同)

时间:2014-09-30 18:28:10

标签: sql sql-server group-by distinct rollup

在获得Group By With Rollup的{​​{1}}时使用Count时遇到了一个小问题。

问题在于,Distinct摘要仅是所有分组中Rollup值的总数,而不是所有分组的摘要。

这是一个测试场景来说明我的意思:

Distinct

对于此特定表,如果我运行此查询:

Create Table #Test
(
    GroupId Int Not Null,
    Value   Int Not Null
)

Insert  #Test (GroupId, Value)
Values  (1, 1),(1, 2),(1, 3),(1, 4),(1, 5),(1, 5),(1, 1),
        (2, 1),(2, 6),(2, 7),(2, 5),(2, 7),(2, 5),
        (3, 9),(3, 10),(3, 11),(3, 4),(3, 5),(3, 7),(3, 8),(3, 5),(3, 7),(3, 8)

我得到以下结果:

Select  Case When Grouping(GroupId) = 1 Then 'Total:' Else Str(GroupId) End As GroupId, 
        Count(Distinct Value) Count
From    #Test
Group By GroupId With Rollup
Order By Grouping(GroupId), GroupId

我对Total行的预期结果是16,但我只得到11 - 这是所有组中GroupId Count ------------- 1 5 2 4 3 7 Total: 11 值的总数。

从查询中删除Distinct确实显示了Distinct的预期结果:

Rollup

产生这些结果:

Select  Case When Grouping(GroupId) = 1 Then 'Total:' Else Str(GroupId) End As GroupId, 
        Count(Value) Count
From    #Test
Group By GroupId With Rollup
Order By Grouping(GroupId), GroupId

总结了预期的群组。

我的问题是:GroupId Count ------------- 1 7 2 6 3 10 Total: 23 上的Rollup是正常的吗?是否有其他Count Distinct - 类似的选项用于Rollup显示16而不是上面示例中的11?

2 个答案:

答案 0 :(得分:2)

您可以通过嵌套查询并使用技巧来获得所需内容:

select GroupId, Sum(Count) as Count
from (Select (Case When Grouping(GroupId) = 1 Then 'Total:' Else Str(GroupId) End) As GroupId, 
             Count(Distinct Value) as Count
      From  #Test
      Group By GroupId
     ) t
Group By GroupId With Rollup
Order By Grouping(GroupId), GroupId;

第二个group by在逻辑上不进行聚合,因为每个组只有一行。只需在rollup中获取您想要的值即可。

答案 1 :(得分:2)

创建测试数据:

DECLARE @Test TABLE
(
    GroupId Int Not Null,
    Value   Int Not Null
)

Insert  @Test 
(GroupId, Value)
Values  (1, 1),(1, 2),(1, 3),(1, 4),(1, 5),(1, 5),(1, 1),
        (2, 1),(2, 6),(2, 7),(2, 5),(2, 7),(2, 5),
        (3, 9),(3, 10),(3, 11),(3, 4),(3, 5),(3, 7),(3, 8),(3, 5),(3, 7),(3, 8)

我将第三列更改为group group by group id AND value

Select  Case When Grouping(GroupId) = 1 Then 'Total:' Else Str(GroupId) End As GroupId, 
       Count(DISTINCT Value) As Count,
        Count(Value) AS Count2,
        Count(DISTINCT (GroupId * 10) + Value) AS Count3
From    @Test
Group By GroupId With Rollup
Order By Grouping(GroupId), GroupId

这是输出:

GroupId Count Count2 Count3
1       5     7      5
2       4     6      4
3       7     10     7
Total:  11    23     16