简体   繁体   中英

Select all columns for a distinct column

I need to fetch distinct rows for a particular column from a table having over 200 columns. How can I achieve this?

I used

Select distinct col1 , * from table;

but it failed.

Please suggest an elegant way to achieve this.

Regards, Tarun

The solution if you want one row for each distinct value in a particular column is:

SELECT col1, MAX(col2), MAX(col3), MAX(col4), ...
FROM mytable
GROUP BY col1

I chose MAX() arbitrarily. It could also be MIN() or some other aggregate function. The point is if you use GROUP BY to make sure to get one row per value in col1, then all the other columns must be inside aggregate functions.

There is no way to write MAX(*) to get that treatment for all columns. Sorry, you will have to write out all the column names (at least those that you need in this query, which might not be all 200).

We can generate a sequence of ROW_NUMBER() for every COL1 and then select the first entry of every sequence.

SELECT * FROM
(
  SELECT E.* , ROW_NUMBER() OVER( PARTITION BY COL1 ORDER BY 1) AS ID
    FROM YOURTABLE E
) MYDATA
 WHERE MYDATA.ID = 1

A working example in fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM