请考虑数据:
Id Group Value ----------------------------------- 1 1 10 2 1 12 3 1 10 4 2 90 5 2 10 6 3 30 7 4 12 8 4 11 9 5 10 10 5 11
我想Group By将此数据1,2,3放在一个组中,4,5放在另一个组中。我该怎么做SQL Server?
Group By
1,2,3
4,5
SQL Server
谢谢
编辑1)
我想要这个结果:
Groups Count ----------------------------------------- Group for 1,2,3 6 Group for 4,5 4
我正在使用,outer apply因此您不会将您的代码复制到组中
outer apply
select C.Group_Name, count(*) from Table1 outer apply ( select case when C.[Group] in (1, 2, 3) then 'Group for 1, 2, 3' when C.[Group] in (4, 5) then 'Group for 4, 5' end as Group_Name ) as C group by C.Group_Name
您还可以使用子查询
select C.Group_Name, count(*) from ( select case when T.[Group] in (1, 2, 3) then 'Group for 1, 2, 3' when T.[Group] in (4, 5) then 'Group for 4, 5' end as Group_Name, T.Value, T.Id from Table1 as T ) as C group by C.Group_Name