创建排名索引

时间:2017-09-25 11:27:37

标签: sql-server

我想要实现的是为我的数据库添加一个连接的排名索引,然后可以将其连接到另一个表。以下是获取结果的当前查询。

select WorksOrderNumber, PartNumber, ScheduledFinishDate
 from vFM_WORKS_ORDER_HEADER 
where Complete = 'No' and ScheduledFinishDate is not null

我想创建一个索引列,其中包含部件号+ ' - ' + a rank number,仅基于该部件号的scheduledFinishedDate(如果有意义的话)

WorksOrderNumber    PartNumber  ScheduledFinishDate Index
28091              100767922    12/01/2018 00:00    100767922 - 2
28300              100767922    09/10/2017 00:00    100767922 - 1 
28092              100767922    26/01/2018 00:00    100767922 - 3 
29166              T1043501     04/12/2017 00:00    T1043501 - 2 
29167              T1043501     25/01/2018 00:00    T1043501 - 3 
29168              T1043501     19/10/2017 00:00    T1043501 -1

问候

1 个答案:

答案 0 :(得分:1)

SELECT
    WorksOrderNumber,
    PartNumber,
    ScheduledFinishDate,
    PartNumber + ' - ' + CONVERT(VARCHAR(10), rn) AS [Index]
FROM
(
    SELECT WorksOrderNumber, PartNumber, ScheduledFinishDate,
        ROW_NUMBER() OVER (PARTITION BY PartNumber ORDER BY ScheduledFinishDate) rn
    FROM yourTable
)