尝试按顺序添加 DENSE_RANK() 的新列

Trying to add new column with DENSE_RANK() in sequentially

我希望一些例子可以帮助解释这种情况。

SELECT 
    ID,
    --ROW_NUMBER() OVER (PARTITION BY CardNumber ORDER BY ID DESC) AS 'RN',
    DENSE_RANK() OVER (ORDER BY CardNumber DESC) AS Rank,
    CardNumber,
    StampNumber,
    AuditDate,
FROM [dbo].[XXXX]
ORDER BY ID DESC, AuditDate DESC, StampNumber DESC

我已经阅读了 DENSE_RANK(),它最接近我正在寻找的内容,但不完全是。 运行 这段代码给了我

ID Rank CardNumber StampNumber AuditDate
46 1 3 20 2022-03-07 03:45:50.343
45 1 3 20 2022-03-07 03:45:50.343
44 2 2 40 2022-03-07 03:45:50.343
43 2 2 30 2022-03-07 03:45:50.343
42 2 2 20 2022-03-07 03:45:50.343
41 2 2 10 2022-03-07 03:45:50.343
40 3 1 40 2022-03-07 03:45:50.343
39 3 1 30 2022-03-07 03:45:50.343
38 3 1 20 2022-03-07 03:45:50.343
37 3 1 10 2022-03-07 03:45:50.343
36 1 3 40 2022-03-07 03:45:50.343
35 1 3 30 2022-03-07 03:45:50.343
34 1 3 20 2022-03-07 03:45:50.343
33 1 3 10 2022-03-07 03:45:50.343

我要找的结果是

ID Rank CardNumber StampNumber AuditDate
46 1 3 20 2022-03-07 03:45:50.343
45 1 3 20 2022-03-07 03:45:50.343
44 2 2 40 2022-03-07 03:45:50.343
43 2 2 30 2022-03-07 03:45:50.343
42 2 2 20 2022-03-07 03:45:50.343
41 2 2 10 2022-03-07 03:45:50.343
40 3 1 40 2022-03-07 03:45:50.343
39 3 1 30 2022-03-07 03:45:50.343
38 3 1 20 2022-03-07 03:45:50.343
37 3 1 10 2022-03-07 03:45:50.343
36 4 3 40 2022-03-07 03:45:50.343
35 4 3 30 2022-03-07 03:45:50.343
34 4 3 20 2022-03-07 03:45:50.343
33 4 3 10 2022-03-07 03:45:50.343

我希望密集排名仍然按 CardNumber 对排名进行分组,但需要排名列按顺序增长而不是重置。 我只希望获得前 3 名。

这是一种 gaps-and-islands 问题。 您正在尝试获取每组相同的排名数字CardNumber 值(无间隙),按 ID DESC.

排序

您不能为此使用 DENSE_RANKROW_NUMBER,因为它们会将具有相同 CardNumber 值的所有行放在一起。

有多种解决方案。这是一个:

WITH PrevValues AS (
     SELECT *,
       IsNewCardNumber = CASE WHEN CardNumber = LAG(CardNumber) OVER (ORDER BY ID DESC)
                        THEN NULL ELSE 1 END
     FROM XXXX
)
SELECT
  ID,
  Rank = COUNT(IsNewCardNumber) OVER (ORDER BY ID DESC),
  CardNumber,
  StampNumber,
  AuditDate
FROM PrevValues;

db<>fiddle