SQL Server组可以替代而不会丢失行

时间:2018-04-20 07:22:16

标签: sql sql-server tsql

我有一个这样的表,需要按名称列分组,但需要保留Ids和Dates 是否有没有XML PATHSTRING_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

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 |
+----+----------+--------------+-------+