开发者

SQL Server - Update a column if row is the first record in group

How do i identify the first row that has value for each Brand and Category, then update Column "FirstValue" as 1, else 0? e.g of expected table

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 |  开发者_StackOverflow社区 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


Common table expressions are actually updatable, and combining CTEs with ranking functions ROW_NUMBER() gives a perfect solution:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜