Skip to content
Advertisement

sql selecting unique rows based on a specific column

I have an table like this :

Col1    Col2    Col3    Col4
asasa   1          d    44
asasa   2         sd    34
asasa   3          f    3
dssd    4          d    2
sdsdsd  5         sd    11
dssd    1         dd    34
xxxsdsds2          d    3
erewer  3          sd   3

I am trying to filter out something like this based on Col1

Col1    Col2    Col3    Col4
asasa   1          d    44
dssd    4          d    2
sdsdsd  5         sd    11
xxxsdsds2          d    3
erewer  3         sd    3

I am trying to get the all unique rows based on the values in Col1. If I have duplicates in Col1, the first row should be taken.

I tried SELECT Col1 FROM tblname GROUP BY Col1 and got unique Col1 but extending it using * is giving me error.

Advertisement

Answer

You should be able to achieve your goal using something like the following:

WITH CTE AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col2) AS rn FROM MyTable
)
SELECT * FROM CTE WHERE rn = 1

What it does is it creates a CTE (Common Table Expression) that adds a ROW_NUMBER on Col1, ordered by the data in row2.

In the outer select, we then only grab the rows from the CTE where the row number generated is 1.

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