postgresql - 如何获取最小值的一行

时间:2017-02-14 08:26:08

标签: sql postgresql greatest-n-per-group

我在这个列

中有表(t_image)
 datacd   | imagecode | indexdate 
----------------------------------
    A     |    1      |  20170213
    A     |    2      |  20170213
    A     |    3      |  20170214
    B     |    4      |  20170201
    B     |    5      |  20170202

期望的结果是这个

    datacd   | imagecode | indexdate 
    ----------------------------------
        A    |    1      |  20170213
        B    |    4      |  20170201

在上表中,我想为每个具有最小索引日期

的datacd检索1行

这是我的查询,但结果返回2行datacd A

select *
from (
   select datacd, min(indexdate) as indexdate
   from t_image
   group by datacd
) as t1 inner join t_image as t2 on t2.datacd = t1.datacd and t2.indexdate = t1.indexdate;

2 个答案:

答案 0 :(得分:4)

Postgres专有distinct on ()运算符通常是查询的最快解决方案:

select distinct on (datacd) *
from t_image
order by datacd, indexdate;

答案 1 :(得分:3)

一个选项使用ROW_NUMBER()

SELECT t.datacd,
       t.imagecode,
       t.indexdate
FROM
(
    SELECT datacd, imagecode, indexdate,
           ROW_NUMBER() OVER (PARTITION BY datacd ORDER BY indexdate) rn
    FROM t_image
) t
WHERE t.rn = 1