Search code examples
sqlcase

Change a value in column b based on when a value in column A changes


I have a data set that looks like the below as a simple example

Date    Description
1/1/24  Testing
1/1/24  Testing
1/2/24  Apple
1/2/24  Apple

What I need to do in SQL is the the end result to look like the below. In short I only need the description on the first row of each date.

Date    Description
1/1/24  Testing
1/1/24  
1/2/24  Apple
1/2/24  

I have tried to think through to see if I could use a case expression but that really doesn't address my issue as I can change column b based on something in column a but I don't know what to put in the case when statement to address to make any secondary same date or more to be blank.


Solution

  • Check this one if you can use CTE.

    declare @Data as table (Dates date, Description nvarchar(50));
    
    insert @Data (Dates, Description)
    values
    ('1/1/24','Testing'),
    ('1/1/24','Testing'),
    ('1/2/24','Apple'),
    ('1/2/24','Apple');
    
    with table_nameCTE AS (  
      select *, row_number() over (partition by Dates, Description order by Dates) as RN  
      from @Data  
    )
    select Dates
      , case when RN = 1 then Description else '' end as Description
    from table_nameCTE