简体   繁体   中英

How do I select a single row for each unique combination of multiple columns?

Table/Data/SQL example: SQLFIDDLE

SELECT
  name,
  p1,
  p2,
  MIN(o1) as o1,
  MIN(o2) as o2
  FROM LOCS l
  GROUP BY l.name, l.p1, l.p2
  ORDER BY name asc

The current SQL I've come up with returns the correct data, but the actual table has 100+ columns and is constantly going to change so there is no way to do MIN() on each column.

I need to select a single row for each combination of "name", "p1", and "p2".

If you want to select to select the "first" row in a grouping, then you can use row_number() -- assuming you have a way of defining "first".

For instance, if the o1 column specifies the ordering, the following gives the row for a particular name , p1 , and p2 combination with the lowest value of o1 :

SELECT l.*
FROM (SELECT l.*, ROW_NUMBER() OVER (PARTITION BY name, p1, p2 ORDER BY o1) as seqnum
      FROM LOCS l
     ) l
WHERE seqnum = 1
ORDER BY name asc;

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