在获得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?
答案 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