我有一张下表:
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
我想用MIN(ID)按CODE分组,并让ID NAME与最小行值匹配 如果具有相同的ID,则获取ID(最小)(DATE) 如果CODE为空,则我不想分组
我希望查询返回以下内容
ID ID NAME PRICE
00001 C 7000
00002 F 2000
00003 E 2000
00004 A 2000
我可以使用什么SQL来获得该结果?
答案 0 :(得分: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