PostgreSQL中的SQL MIN(值)匹配行

时间:2018-09-12 10:39:52

标签: sql postgresql

我有下表:

表A:

 ID          ID NAME      PRICE         CODE      
 00001          B         1000          1       
 00002          A         2000          1       
 00003          C         3000          1       

这是我使用的SQL:

Select Min (ID),
       Min (ID NAME),
       Sum(PRICE)
From A
GROUP BY CODE

这就是我得到的:

ID         ID NAME     PRICE         
00001       A          6000   

如您所见,ID NAME与最小行值不匹配。我需要他们配合。

我希望查询返回以下内容

ID         ID NAME     PRICE         
00001       B          6000  

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

3 个答案:

答案 0 :(得分:0)

如果要排一行,请使用limitfetch first 1 row only

select a.*
from a
order by a.price asc
fetch first 1 row only;

如果出于某些原因想要所有价格的 sum(),则可以使用窗口函数:

select a.*, sum(a.price) over () as sum_prices
from a
order by a.price asc
fetch first 1 row only;

答案 1 :(得分:0)

您可以使用row_number()函数:

select min(id), max(case when seq = 1 then id_name end) as id_name, sum(price) as price, code
from (select t.*, row_number() over (partition by code order by id) seq
      from table t
     ) t
group by code;

答案 2 :(得分:0)

您还可以使用子查询

select t1.*,t2.* from
(select ID,Name from t where ID= (select min(ID) from t)
) as t1
cross join (select sum(Price) as total from t) as t2

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

id  name    total
1    B      6000