Skip to content
Advertisement

How to get single row from multiple rows having same ID?

I have multiple rows for same ID. How to display any one row per unique ID?

I tried

select Col_1, Col_2, Col_3 from Table group by Col_1. 

But this throws error saying, Col_2 and Col_3 is not in group by clause ( I wonder if syntax is wrong )

this is the given table

Col_1  Col_2  Col_3
1        A       B
1        B       A
2        C       D
2        D       C

Expected Output

Col_1  Col_2  Col_3
1        A       B
2        C       D

Advertisement

Answer

You are very close… when using group by , columns that are not part of the grouping statement must be part of an aggregate function. As such you can do something like:

select Col_1, Max(Col_2), Max(Col_3) from Table group by Col_1

I used the max Aggregation function here, but you can use any function you want. The above should get you what you are looking for and should run on most DBs

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement