如何识别每个品牌和类别的第一行,然后将“FirstValue”列更新为1,否则为0? 例如预期表
Date | Brands | Category | Value | FirstValue
Jan 08 | A | 1 | 0 |0
Jan 08 | A | 2 | 0 |0
Jan 08 | A | 3 | 0 |0
Jan 08 | B | 1 | 12 |1
Jan 08 | B | 2 | 0 |0
Jan 08 | B | 3 | 0 |0
Feb 08 | A | 1 | 5 |1
Feb 08 | A | 2 | 0 |0
Feb 08 | A | 3 | 67 |1
Feb 08 | B | 1 | 0 |0
Feb 08 | B | 2 | 0 |0
Feb 08 | B | 3 | 6 |1
答案 0 :(得分:2)
Common table expressions实际上是可更新的,将CTE与排名函数ROW_NUMBER()
结合起来可以提供完美的解决方案:
with cte as (
select row_number() over (partition by Brand, Category order by Date) as rn
, FirstValue
from Table)
update cte
set FirstValue = case when rn = 1 then 1 else 0 end;