[英]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.