[英]postgresql - How to get one row the min value
我有这个列的表(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行
这是我的查询,但结果为datacd A返回2行
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 ()
运算符通常是针对每组最大查询的最快解决方案:
select distinct on (datacd) *
from t_image
order by datacd, indexdate;
一个选项使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.