T-SQL - Dense_Rank返回奇怪的数字

时间:2018-01-09 13:06:39

标签: sql sql-server tsql dense-rank

以下Dense_Rank查询返回非常奇怪的输出:

SELECT DENSE_RANK() OVER(PARTITION BY ColC ORDER BY ColB) AS [Rank]
FROM
(
    SELECT *,
           concat(ColA, CONVERT(DATE, ColB)) AS ColC
    FROM ##Table
) Subquery1;

返回:

ColB                ColC   Rank
01/11/2017 14:06    ValueA  3
01/11/2017 16:06    ValueA  5
01/11/2017 16:09    ValueA  6
01/11/2017 16:17    ValueA  7
02/11/2017 12:19    ValueB  2
02/11/2017 16:00    ValueB  5
02/11/2017 16:09    ValueB  6
02/11/2017 16:19    ValueB  7
02/11/2017 16:28    ValueB  8
02/11/2017 16:37    ValueB  9

相对排名似乎是正确的,但分配给每个排名的数字都很奇怪。为什么价值A没有数字1,2或4?为什么数字1中缺少数字1,3和4?

1 个答案:

答案 0 :(得分:0)

您没有显示实际查询,但我很确定,您的观察与此有关:

DECLARE @tbl TABLE(ID INT IDENTITY, RankingValue INT);
INSERT INTO @tbl VALUES (1),(2),(3),(8),(3),(2),(9),(0);

- 此查询在排名

之前应用WHERE过滤器
SELECT *
      ,DENSE_RANK() OVER(ORDER BY RankingValue) AS TheRank
FROM @tbl
WHERE RankingValue>3;

- 结果

ID  RankingValue    TheRank
4   8               1
7   9               2

- 此查询适用过滤器以后

WITH cte AS
(
    SELECT *
          ,DENSE_RANK() OVER(ORDER BY RankingValue) AS TheRank
    FROM @tbl
)
SELECT * 
FROM cte
WHERE RankingValue>3;

- 结果

ID  RankingValue    TheRank
4   8               5        <-- Your weird values... ??
7   9               6