SQL Server - 如果row是组中的第一个记录,则更新列

时间:2010-07-01 03:29:15

标签: sql sql-server group-by sql-update

如何识别每个品牌和类别的第一行,然后将“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

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;