与PostgreSQL 2中的行匹配的SQL最小值(值)
我有下表:与PostgreSQL 2中的行匹配的SQL最小值(值),sql,postgresql,Sql,Postgresql,我有下表: 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
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)按代码分组,并使ID名称与min行值匹配
如果具有相同的ID,则获取ID名称(日期)
如果代码为空,我不想分组
我希望查询返回以下内容
ID ID NAME PRICE
00001 C 7000
00002 F 2000
00003 E 2000
00004 A 2000
我可以使用什么样的SQL来获得该结果?根据下面查询的示例数据
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
我不明白为什么
0005
会被过滤掉,但是0004
会出现在期望的结果中。你的期望结果与你的要求相矛盾。这与你之前的问题有什么不同:0004的代码为“null”,而0005的代码为2,与0002相同。我对这个问题投了赞成票,因为这个问题对你来说非常清楚我。C的价格应该是7000而不是3000。谢谢,但我有附加条件使用日期。如果组具有相同的ID,则获取ID名称的最小值(日期)
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