我正在使用DENSE_RANK
为每个组[y]
中的[x]
的不同值分配序号。它添加了一个新列[rank]
。
我还想要一个新列,显示每个[y]
内的最高等级[x]
(最高序列号),例如[highest_rank]
。有没有办法同时获取这个新列,而不必为最大值创建一个单独的表,然后将表连接在一起?
SELECT [x],[y],[rank]
INTO table2
FROM
(
SELECT *, DENSE_RANK() OVER (PARTITION BY [x] ORDER BY [y] ) AS [rank]
FROM table1
) tmp
答案 0 :(得分:0)
如果我理解正确,你就会找到这样的东西:
;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];