[英]SQL MIN(value) matching row in PostgreSQL
I have a following tables: 我有以下表格:
TABLE A: 表A:
ID ID NAME PRICE CODE
00001 B 1000 1
00002 A 2000 1
00003 C 3000 1
Here is the SQL I use: 这是我使用的SQL:
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. 如您所见,ID NAME与最小行值不匹配。 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? 我可以使用哪种SQL来获得该结果?
If you want one row, use limit
or fetch first 1 row only
: 如果需要一行,请使用limit
或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: 如果由于某种原因,您想要所有价格的sum() ,则可以使用窗口函数:
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 : 您可以使用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;
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 https://dbfiddle.uk/?rdbms=postgres_10&fiddle=a496232b552390a641c0e5c0fae791d1
id name total
1 B 6000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.