Search code examples
duplicatessql-order-byordereddictionary

sql or python solution for getting merging duplicate rows into one in an ordered table and reordering them


Can someone help me do this in SQL in a select statement? I have a table xyz as follow:

ColumnID Column A Column B
1 1 A
1 2 B
1 3 C
1 4 D
2 1 A
2 2 B
2 3 C
2 4 C
3 1 A
3 2 A
3 3 B
3 4 B
4 1 A
4 2 B
4 3 V
4 4 V

I want it to change to this:

Column A Column B
1 A
2 B
3 C
4 D
1 A
2 B
3 C
1 A
2 B
1 A
2 B
3 V

haven't tried anything


Solution

  • Here is the solution for anyone who has the same question:

    with abc as (select  columnID, ROW_NUMBER() over (PARTITION by columnID, column_b   ORDER BY columnID) as column_a, column_b 
                    from xyz)
        select  row_number() over (partition by columnID order by column_a asc) as column_a, column_b
        from abc where row_num = 1