我有一个SQL查询,其中包含3个int
列,然后是3个Rank()
函数,其中partition by
对这3列进行排名。
问题是,我只想为每列排名高达5000,然后在此之后停止。无论如何在单个查询中执行此操作而不将其拆分为3个查询?我仍然想要前3列的所有数据,只需要{5000}后的Rank()
列为空。
每个分区最多可达5000个。
由于
答案 0 :(得分:3)
您可以使用案例陈述。
...
CASE WHEN ROW_NUMBER() OVER (<partition by>) <= 5000
THEN <rank function>
ELSE NULL
END
...
答案 1 :(得分:1)
扩展Joe Stefanelli的解决方案:
;with cte as (
select a, b, c,
rank() over (partition by ...) as [r1],
rank() over (partition by ...) as [r2],
rank() over (partition by ...) as [r3]
from your_table
)
select a, b, c,
case when [r1] <= 5000 then [r1] else null end as [r1]
case when [r2] <= 5000 then [r1] else null end as [r2]
case when [r3] <= 5000 then [r1] else null end as [r3]
from cte
答案 2 :(得分:0)
RANK()函数将类似的值视为类似的等级,因此NULL获得相同的等级。所以解决方案是使用ROW_NUMBER()。