ItemID | NumberOfUses | LastMaint | Partition
0111 1 NULL 1
0111 1 1/1/2015 2
0111 2 1/1/2015 2
0111 3 1/1/2015 2
0111 4 1/1/2015 2
0111 5 1/1/2015 2
0111 1 4/1/2015 3
0111 2 4/1/2015 3
0111 3 4/1/2015 3
0111 1 7/1/2015 4
0111 2 7/1/2015 4
0111 3 7/1/2015 4
0111 4 7/1/2015 4
0111 5 7/1/2015 4
0111 6 7/1/2015 4
0111 7 7/1/2015 4
0111 8 7/1/2015 4
0111 9 7/1/2015 4
我想弄清楚的是如何让Partition列看起来像上面那样。 (我在不同的组/分区之间添加了一个空格,以便于查看)。
我一直试图使用接近下面查询的内容来做这件事。我在ROW_NUMBER()OVER()
中尝试了几乎所有列的组合SELECT [ItemID]
,[NumberOfUses]
,[LastMaintenance]
,ROW_NUMBER() OVER (PARTITION BY ?????????
ORDER BY ???????) [Partition]
FROM [ItemsHistory]
ORDER BY [Partition]
答案 0 :(得分:2)
尝试DENSE_RANK:
SELECT [ItemID]
,[NumberOfUses]
,[LastMaintenance]
,DENSE_RANK() OVER (PARTITION BY [ItemId] ORDER BY [LastMaintenance]) [Partition]
FROM [ItemsHistory]
ORDER BY [ItemId], [Partition], [NumberOfUses]