PostgreSQL 2中的SQL MIN(值)匹配行

问题描述 投票:-1回答:1

我有一张桌子:

  ID          ID NAME      PRICE        DATE             CODE
 00003          E           2000      2018/03/24        null        
 00001          C           3000      2018/03/22         1   
 00001          D           4000      2018/03/23         1  
 00002          F           1000      2018/03/21         2   
 00005          B           1000      2018/03/21         2  
 00004          A           2000      2018/03/24        null  

我想用CODE与min(ID)分组并获取ID NAME与min行值匹配如果有相同的ID,获取ID NAME哪个Min(DATE)如果CODE为null,我不想分组

我想查询返回以下内容

 ID         ID NAME     PRICE       
00001         C         7000
00002         F         2000
00003         E         2000
00004         A         2000

我可以用什么SQL来获得结果?

sql postgresql
1个回答
0
投票

根据您需要在下面查询的示例数据

with cte1 as
(
select t.code, min(date1) as date1 ,max(t1.s) as price from t
join

(
select code,sum(price) as s  from t where code is not null group by code
) t1 on t.code=t1.code
group by t.code
),
cte2 as
(
select min(t.id) as id ,t.date1,cte1.price from cte1 join t on cte1.date1=t.date1 group by t.date1,cte1.price
) ,

cte3 as 
(
select cte2.*,t.name from cte2 join t on cte2.id=t.id and cte2.date1=t.date1
) ,
cte4 as
(
select * from cte3 union select id,date1,price,name from t where code is null
) select * from cte4 order by id

https://dbfiddle.uk/?rdbms=postgres_10&fiddle=77e2269b6c7e7b48a8039824e15c66fb

id  date1   price      name
1   2018-03-22  7000    C
2   2018-03-21  2000    F
3   2018-03-24  2000    E
4   2018-03-24  2000    A
© www.soinside.com 2019 - 2024. All rights reserved.