我在这个列
中有表(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;
答案 0 :(得分:4)
Postgres专有distinct on ()
运算符通常是greatest-n-per-group查询的最快解决方案:
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