TSQL行号按参考和日期划分

时间:2019-10-17 15:47:18

标签: tsql row

使用带有下面参考和日期列示例的单个表,如何生成下面的输出以拆分行号。同一天的同一引用应显示为相同的行号。

以下示例;

MAINFRAJOB  SyncDate    Row Number
7861    02/10/2019  1
7861    02/10/2019  1
7861    03/10/2019  2
1045679 25/09/2019  1
10233649    03/10/2019  1
10233652    04/10/2019  1
10233652    04/10/2019  1
10233652    06/10/2019  2
123456789   02/10/2019  1
123456789   02/10/2019  1
123456789   03/10/2019  2
123456789   04/10/2019  3

我已经尝试过了,但是没有产生正确的结果;

ROW_NUMBER()over(partition by cast(ard.SyncDate as date), ard.actionref order by cast(ard.SyncDate as date) desc) AS 'RowNo'

感谢您的指导。

2 个答案:

答案 0 :(得分:0)

请改为尝试DENSE_RANK,您还需要从分区中删除日期,否则每次更改日期时该分区都会重置为1:

DENSE_RANK()over(partition by cast(ard.SyncDate as date), ard.actionref order by cast(ard.SyncDate as date) desc) AS 'RowNo'

答案 1 :(得分:0)

我认为您确实正在寻找BarneyL提到的Dense_Rank(),但您也想按MAINFRAJOB进行分区

示例

Select *
      ,Row_Number = DENSE_RANK() over (Partition By [MAINFRAJOB] Order by [SyncDate])
 From YourTable

返回

enter image description here