我有一个这样的表,需要按名称列分组,但需要保留Ids和Dates
是否有没有XML PATH
或STRING_AGG
Id Name Date
1 Apple 2018/20/04
2 Apple 2018/20/03
3 Orange 2018/20/01
4 Apple 2018/20/02
5 Orange 2018/20/03
按名称分组应该= =>
Id Name Date Group
1 Apple 2018/20/04 1
2 Apple 2018/20/03 1
3 Orange 2018/20/01 2
4 Apple 2018/20/02 1
5 Orange 2018/20/03 2
答案 0 :(得分:4)
你可以试试这个。
使用DENSE_RANK
功能,然后ORDER BY ID
保持order
为asc
SELECT Id,Name,Dates,DENSE_RANK() OVER(ORDER BY NAME) 'GROUP'
FROM T2
ORDER BY ID
sqlfiddle:http://sqlfiddle.com/#!18/10652/1
答案 1 :(得分:0)
尝试这样的事情。
Select [ID], [Name], [Date],
ROW_NUMBER() over (partition by [Name] order by [ID]) as [Group]
from TableName
结果
+----+----------+--------------+-------+
| ID | Name | Date | Group |
+----+----------+--------------+-------+
| 1 | Apple | 2018/20/04 | 1 |
| 2 | Apple | 2018/20/03 | 2 |
| 4 | Apple | 2018/20/02 | 3 |
| 3 | Orange | 2018/20/01 | 1 |
| 5 | Orange | 2018/20/03 | 2 |
+----+----------+--------------+-------+