简体   繁体   English

如何为多列的每种唯一组合选择一行?

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

Table/Data/SQL example: SQLFIDDLE 表/数据/ SQL示例: 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. 我提出的当前SQL返回正确的数据,但是实际表有100多个列,并且会不断变化,因此没有办法对每一列进行MIN()。

I need to select a single row for each combination of "name", "p1", and "p2". 我需要为“名称”,“ p1”和“ 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". 如果要选择在分组中选择“第一”行,则可以使用row_number() -假设您已定义了“第一”行。

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 : 例如,如果o1列指定顺序,则下面的行给出了具有最低o1值的特定namep1p2组合:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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