如果值在“OVER(order by something)”组中最后得到“1”,如果不是则为“0”?

时间:2014-02-26 06:15:15

标签: sql sql-server tsql

我使用窗口函数进行简单查询:

select
    productId, 
    is_last = row_number() over( order by productId ) 
from [productstatuses] order by ProductID

如果当前记录在“over(order by productId)”组中为最后一个,则如何修改“is_last”以获得1作为值,如果不是,则如果当前记录为0,则如何修改为

更新:感谢@TechDo,我的问题的最终解决方案是:

select
    productId, 
    is_last = iif(count(*) over(order by productId)=row_number() over(order by productId), 1, 0)
from [productstatuses] order by ProductID

1 个答案:

答案 0 :(得分:2)

请尝试:

select
    productId, 
    is_last = case when COUNT(*) OVER()=row_number() over(order by productId) then 1 else 0 end
from [productstatuses] order by ProductID