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

安稳与你 提交于 2019-12-12 05:39:51

问题


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 |   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:


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;


来源:https://stackoverflow.com/questions/3154911/sql-server-update-a-column-if-row-is-the-first-record-in-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!