2017-02-14 166 views
1

我已经表(t_image)与此列PostgreSQL的 - 如何获得一个行最小值

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; 
+0

http://stackoverflow.com/questions/ tagged/postgresql + most-n-group- –

回答

2

Postgres的专有distinct on()运营商通常为查询最快的解决方案:

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

这一个工程..但性能明智,查询变得慢一点.. – john1717

+0

反正谢谢.. – john1717

+0

@ john1717:如果你有性能问题,请阅读[postgresql-performance](http://stackoverflow.com/tags/postgresql-performance/info),然后询问一个新的问题,提供来自标签描述的信息 –

2

可以选择使用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 
+0

它也在工作..感谢 – john1717

相关问题