使用 DENSE_RANK 的序号和最大值
Sequential number and maximum value using DENSE_RANK
我正在使用 DENSE_RANK
为每个组 [x]
中的 [y]
的不同值分配一个序列号。它添加了一个新列 [rank]
.
我还想要一个新列,显示每个 [x]
中的最大排名 [y]
(最高序列号),例如[highest_rank]
。有没有办法同时获得这个新列,而不必为最大值创建一个单独的 table 然后将 table 连接在一起?
SELECT [x],[y],[rank]
INTO table2
FROM
(
SELECT *, DENSE_RANK() OVER (PARTITION BY [x] ORDER BY [y] ) AS [rank]
FROM table1
) tmp
如果我没理解错的话,你正在寻找这样的东西:
;WITH cte1 AS (
SELECT *,DENSE_RANK() OVER (PARTITION BY [x] ORDER BY [y] ) AS [rank]
FROM table1
),
cte2 AS (
SELECT [x], [highest_rank]=MAX([rank])
FROM cte1
GROUP BY [x]
)
SELECT cte1.[x],cte1.[y],cte1.[rank],cte2.[highest_rank]
FROM cte1 INNER JOIN cte2 ON cte2.[x]=cte1.[x];
我正在使用 DENSE_RANK
为每个组 [x]
中的 [y]
的不同值分配一个序列号。它添加了一个新列 [rank]
.
我还想要一个新列,显示每个 [x]
中的最大排名 [y]
(最高序列号),例如[highest_rank]
。有没有办法同时获得这个新列,而不必为最大值创建一个单独的 table 然后将 table 连接在一起?
SELECT [x],[y],[rank]
INTO table2
FROM
(
SELECT *, DENSE_RANK() OVER (PARTITION BY [x] ORDER BY [y] ) AS [rank]
FROM table1
) tmp
如果我没理解错的话,你正在寻找这样的东西:
;WITH cte1 AS (
SELECT *,DENSE_RANK() OVER (PARTITION BY [x] ORDER BY [y] ) AS [rank]
FROM table1
),
cte2 AS (
SELECT [x], [highest_rank]=MAX([rank])
FROM cte1
GROUP BY [x]
)
SELECT cte1.[x],cte1.[y],cte1.[rank],cte2.[highest_rank]
FROM cte1 INNER JOIN cte2 ON cte2.[x]=cte1.[x];