在PostgreSQL中,如何返回与值min相对应的整行?

时间:2015-06-19 20:58:30

标签: sql postgresql min amazon-redshift

所以如果我有这样的表

id | value | detail
-------------------
12 | 20    | orange
12 | 30    | orange
13 | 16    | purple
14 | 50    | red
12 | 60    | blue

我怎样才能让它返回?

12 | 20 | orange
13 | 16 | purple
14 | 50 | red

如果按ID和详细分组,则返回12 | 20 |橙色和12 | 60 |蓝色

4 个答案:

答案 0 :(得分:3)

SQL Fiddle

PostgreSQL 9.3架构设置

CREATE TABLE TEST( id INT, value INT, detail VARCHAR );
INSERT INTO TEST VALUES ( 12, 20, 'orange' );
INSERT INTO TEST VALUES ( 12, 30, 'orange' );
INSERT INTO TEST VALUES ( 13, 16, 'purple' );
INSERT INTO TEST VALUES ( 14, 50, 'red' );
INSERT INTO TEST VALUES ( 12, 60, 'blue' );

查询1

不确定Redshift是否支持此语法:

SELECT DISTINCT
       FIRST_VALUE( id ) OVER wnd AS id,
       FIRST_VALUE( value ) OVER wnd AS value,
       FIRST_VALUE( detail ) OVER wnd AS detail
FROM   TEST
WINDOW wnd AS ( PARTITION BY id ORDER BY value )

<强> Results

| id | value | detail |
|----|-------|--------|
| 12 |    20 | orange |
| 14 |    50 |    red |
| 13 |    16 | purple |

查询2

SELECT t.ID,
       t.VALUE,
       t.DETAIL
FROM (
  SELECT *,
         ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY VALUE ) AS RN
  FROM   TEST
) t
WHERE  t.RN = 1

<强> Results

| id | value | detail |
|----|-------|--------|
| 12 |    20 | orange |
| 13 |    16 | purple |
| 14 |    50 |    red |

答案 1 :(得分:1)

对于窗口聚合函数,这是一项简单的任务,ROW_NUMBER:

select *
from
 (
   select t.*,
      row_number() 
      over (partition by id        -- for each id
            order by value) as rn  -- row with the minimum value
   from t
 ) as dt
where rn = 1

答案 2 :(得分:1)

Postgres有一个DISTINCT ON条款来解决这个案子。对于DISTINCT ON (id),查询将仅返回id的每个值的第一条记录。您可以通过ORDER BY子句控制选择哪条记录。在你的情况下:

SELECT DISTINCT ON (id) *
FROM t
ORDER BY id, value

答案 3 :(得分:0)

使用order bylimit

select t.*
from table t
order by value
limit 1;

如果您在value上有索引,则返回所有匹配行的替代方法是:

select t.*
from table t
where value = (select min(value) from table t);

如果您只想要一行,请添加limit