简体   繁体   中英

select a specific value in a group by statement using postgresql

for instance i have this table

prices

    price   |   location
------------+-------------
 2.50       | U express
 2.19       | Carrefour

if I request

SELECT avg(price), min(price), max(price) FROM prices GROUP BY price;

I will get

  avg   |  min  |  max  
--------+-------+-------
2.34500 | 2.19  | 2.50

Is it possible to get the following result using only one sql statement ?

  avg   |  min  |  max  |  minLocation  | maxLocation
--------+-------+-------+---------------+-------------
2.34500 | 2.19  | 2.50  | Carrefour     |  U express

minLocation is the value in the "location" column for which the price is the lowest. And maxLocation , for which the price is the highest.

There are various ways. One method is to use a subquery:

select avg(price), min(price), max(price),
       max(case when seqnum_a = 1 then location end) as min_location,
       max(case when seqnum_d = 1 then location end) as max_location
from (select p.*, row_number() over (order by price desc) as seqnum_d,
             row_number() over (order by price asc) as seqnum_a
      from prices p
     ) p;

This is just one solution. Postgres offers arrays, a wealth of window functions, and the filter clause (which is a bit faster) that offer other solutions as well. The above is standard SQL and reasonable.

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