sqlsql-serverpartition

Column comparison between rows of the same group used in Partition By clause


I want to compare same columns of rows falling into the same group created by partition by clause in SQL. My table has below data:

Id  Serial_Number   Last_update_date    Flag
1   3344            07-05-2024          N
2   3344            02-05-2024          N
3   9098            20-02-2024          Y
4   9098            20-02-2024          Y
5   2323            07-03-2023          Y
6   2323            17-10-2023          Y
7   2323            17-10-2023          Y
8   1894            10-07-2022          N
9   1894            20-02-2024          N
10  1894            02-05-2024          N

In the above data, grouping should be done by Serial_Number column and should check if any 2 dates within a serial_number are same, the flag for all the group members should be Y, otherwise all should be N. I tried using count(distinct last_update_date) over partition by serial_number but it is not working.

with cte as (
  select a.*, count(distinct last_update_date) 
                   over (partition by serial_number) as cnt
  from my_table a
)
select * from cte 

Solution

  • If any 2 dates in partition is equal then max(dense_rank()) < count(*) for this partition.

    with cte as (
      select a.*
        ,dense_rank()over (partition by serial_number order by last_update_date) as rnk
      from my_table a
    )
    select * 
      ,case when max(rnk)over(partition by serial_number)
                   < count(*)over(partition by serial_number) 
           then 'Y' 
       else 'N' 
       end flag
    from cte 
    order by id
    
    Id Serial_Number Last_update_date rnk flag max_rnk cnt
    1 3344 2024-05-07 2 N 2 2
    2 3344 2024-05-02 1 N 2 2
    3 9098 2024-02-20 1 Y 1 2
    4 9098 2024-02-20 1 Y 1 2
    5 2323 2023-03-07 1 Y 2 3
    6 2323 2023-10-17 2 Y 2 3
    7 2323 2023-10-17 2 Y 2 3
    8 1894 2022-07-10 1 N 3 3
    9 1894 2024-02-20 2 N 3 3
    10 1894 2024-05-02 3 N 3 3

    demo