Skip to content Skip to sidebar Skip to footer

Sql - Replace Repeated Rows With Null Values While Preserving Number Of Rows

I am trying to get only one instance of a year instead of 12 because I am using this column in a lookup table to provide parameters to a report. Because I am using both monthly and

Solution 1:

You can do this by enumerating the rows within a year. Then update all but the first:

with toupdate as (
      select t.*, row_number() over (partitionby [year] orderby [date]) as seqnum
      from t
     )
update toupdate
    set [year] =NULLwhere seqnum >1;

If you want this as a select statement:

with ts as (
      select t.*, row_number() over (partitionby [year] orderby [date]) as seqnum
      from t
     )
select [date],
       (casewhen seqnum =1then [year] end) as [year]
from ts;

Post a Comment for "Sql - Replace Repeated Rows With Null Values While Preserving Number Of Rows"