[英]SQL row_number() with conditions
I have the following information in SQL Server table: 我在SQL Server表中具有以下信息:
How can I add C1-C2-C3-C4 columns? 如何添加C1-C2-C3-C4列? To do this each colum has different conditions.
为此,每个列都有不同的条件。 I'm using
row_number() order by id_pv desc
, but it doesn't work. 我正在
row_number() order by id_pv desc
使用row_number() order by id_pv desc
,但是它不起作用。
I think you can do this with nested case statements -- both in the partition by
clause and outside the row_number()
. 我认为您可以使用嵌套的case语句来做到这一点-既可以在
partition by
子句中,也可以在row_number()
。 For the first column: 对于第一列:
select t.*,
(case when expiry_date > @somdate and
row_number() over (partition by cod_suc, cod_ramo,
(case when expiry_date > @somdate then 1 else 0 end)
order by id_pv desc) as col1
then 1 else 0
end)
from table t;
Assuming from your example you want it to place 0 when your conditions are not met, and the row number otherwise, try: 从您的示例假设,您希望在不满足条件时将其置于0,否则将其置于行号,请尝试:
Select [your columns]
, case when ExpiryDate >= @someDate then row_number()
over (order by [list of columns])
else 0 end as c1
, case when ExpiryDate >= @someDate and Cod_grupo = 4 then row_number()
over (order by [other list of columns])
else 0 end as c2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.