如何将编号的行分组

时间:2016-12-29 21:03:19

标签: sql sql-server

在Sql Server中,我需要重复一组行号并将它们分组成段或子组。我试图使用Sql实现B列。我使用row_number()函数实现了列a,但我不知道如何到达B列。

这是row_number()

的逻辑

1 +((row_number()over(按TimeStamp,FileName,OrderID排序) - 1)%5)AS [Row_Number]

enter image description here

2 个答案:

答案 0 :(得分:2)

您的row_number()格式为:

row_number() over (partition by colA order by colB)

您似乎想要的是:

dense_rank() over (order by colA)

也就是说,row_number()使用的分区键应该是order by的{​​{1}}键。

编辑:

您的代码是:

dense_rank()

在这种情况下,没有1 + ((row_number() over (order by TimeStamp, FileName, OrderID) - 1) % 5) AS [Row_Number] 。你真正想要的只是整数除法。这很简单:

partition by

答案 1 :(得分:0)

我会选择一个简单的解决方案:

SELECT [Row_Number], GroupNumber
FROM (
    SELECT [Row_Number]
        , row_number()over(partition by [Row_Number] order by [Row_Number]) as GroupNumber
        --Note: The order by clause above should be replaced with however you are ordering the groups of row numbers)
    FROM YourTableOrInlineView
    ) z
ORDER BY GroupNumber, [Row_Number]