在sql中命名分组集

时间:2015-02-26 05:31:32

标签: tsql sql-server-2008-r2 group-by

是否可以将组名添加到T-SQL

中的分组集
Select Class, Category, Gender,Count(1) as Total, 'GroupNameHere' from PersonTable
Group By Class, Category, Gender

我希望每个分组都有一个新名称,如下所述

实际表格

Name     |    Class   |   Category   |   Gender   |   Address   |   ZipCode
----------------------------------------------------------------------------
ABC      |      2     |     Cat 1    |     M      |  Some Add.. |   10125
XYZ      |      2     |     Cat 1    |     M      |  Some Add.. |   20554
AFF      |      3     |     Cat 3    |     M      |  Some Add.. |   24525
ASD      |      7     |     Cat 6    |     F      |  Some Add.. |   18892
GDS      |      7     |     Cat 6    |     F      |  Some Add.. |   17745

输出

Class |   Category   |   Gender   |   Total   |   GroupName
----------------------------------------------------------------------------
2     |     Cat 1    |     M      |     2     |   Group 1
3     |     Cat 3    |     M      |     1     |   Group 2
7     |     Cat 6    |     F      |     2     |   Group 3

2 个答案:

答案 0 :(得分:2)

Select Class, Category, Gender,Count(1) as Total,  'Group ' +CAST (Row_Number() over ( order by Class, Category, Gender) as varchar(10) )as GroupName 
from PersonTable 
Group By Class, Category, Gender

答案 1 :(得分:0)

通过引用this获得解决方案。我可以使用NewId()生成基于GUID的行ID。

Select Class, Category, Gender,Count(1) as Total, 
'Group' + Convert(varchar(100),(ABS(CHECKSUM(NewId())))) as GroupName from PersonTable
Group By Class, Category, Gender