简体   繁体   中英

SQL MIN(value) matching row in PostgreSQL

I have a following tables:

TABLE A:

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

Here is the SQL I use:

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

Here is what I get:

ID         ID NAME     PRICE         
00001       A          6000   

As you can see, ID NAME don't match up with the min row value. I need them to match up.

I would like the query to return the following

ID         ID NAME     PRICE         
00001       B          6000  

What SQL can I use to get that result?

If you want one row, use limit or fetch first 1 row only :

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

If, for some reason, you want the sum() of all prices, then you can use window functions:

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

You can use row_number() function :

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;

you can also use sub-query

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM