我有这个栏目的桌子(图)

 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检索一行
这是我的查询,但结果为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;

最佳答案

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

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

关于sql - postgresql-如何获得一行的最小值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42221108/

10-10 00:34