我在获取Group By With Rollup的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我得到了以下结果:
GroupId Count
-------------
1 5
2 4
3 7
Total: 11 我对总计行的预期结果是16,但是我只得到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-like选项可供Grouping显示16而不是11?
发布于 2014-09-30 18:43:53
通过嵌套查询并使用技巧,您可以得到想要的东西:
select (Case When Grouping(GroupId) = 1 Then 'Total:' Else Str(GroupId) End) as GroupId,
Sum(Count) as Count
from (Select 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中获得您想要的值。
发布于 2014-09-30 19:01:30
创建测试数据:
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)我将第三列改为组id和值不同的组。
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 16https://stackoverflow.com/questions/26127637
复制相似问题