如何在GROUP BY sql语句中检索特定列?

时间:2014-09-17 12:59:31

标签: sql database postgresql greatest-n-per-group

airports

 id | from | to | price | photo | notes
 _______________________________________
  1 | LON  | JFK|  1000 |       | test
  2 | LON  | JFK|  2000 |       | test2

我想检索数据库中所有from-to组合的最佳价格条目。 我想获取找到minprice的整个记录​​,或者至少是特定的表。

以下作品,但只给我3个列,从,到,价格。不是整个实体。

SELECT from, to, min(price) FROM airports GROUP BY from, to

我怎么能适应这个?

5 个答案:

答案 0 :(得分:4)

这通常使用窗口函数完成:

select id, "from", "to", price, photo, notes
from (
    select id, "from", "to", price, photo, notes
           min(price) over (partition by "from", "to") as min_price
    from the_table
) t
where price = min_price
order by id;

from是保留字,将其用作列名称(不完全确定to

是一个坏主意。

处理" tie" (在from,to和price中的值相同),您可以使用dense_rank()函数:

select id, "from", "to", price, photo, notes
from (
    select id, "from", "to", price, photo, notes
           dense_rank() over (partition by "from", "to" order by price) as price_rank
    from the_table
) t
where price_rank = 1
order by id;

答案 1 :(得分:1)

您可以订购结果并使用distinct on来获取每个分组的第一个结果

select distinct on (from,to) * from airports order by from,to,price asc;

以上查询应该有效

答案 2 :(得分:1)

一个非常简单的解决方案就是这样。 SQLFiddle here

SELECT * 
FROM airports 
WHERE (from_place, to_place, price) =
(SELECT from_place, to_place, min(price) 
FROM airports 
GROUP BY from_place, to_place);

使用SELECT * FROM ...,因为您需要整个实体。

答案 3 :(得分:0)

如果您想获取整个数据,这是一个解决您问题的查询:

SELECT A.*
FROM airports A
INNER JOIN (SELECT A2.fromhere
                 ,A2.tohere
                 ,MIN(A2.price) AS minprice
            FROM airports A2
            GROUP BY A2.fromhere, A2.tohere) T ON T.fromhere = A.fromhere
                                          AND T.tohere = A.tohere
                                          AND T.minprice = A.price

该联合会用于获得每对夫妇最优惠的价格。

希望这会对你有所帮助。

答案 4 :(得分:0)

没有办法成为一个整个实体"您的表格中可能有很多行可能包含从+到+最低价格的匹配

例如,如果您的表包含

id | from | to | price | photo | notes
 _______________________________________
  1 | LON  | JFK|  1000 |       | test
  2 | LON  | JFK|  2000 |       | test2
  3 | LON  | JFK|  5000 |       | test3
  4 | LON  | JFK|  2000 |       | test4
  5 | LON  | JFK|  1000 |       | test5

然后第1行和第5行都符合从+到+ min价格的标准。

您可以编写查询

SELECT id, from, to, price, photo, notes
FROM airports a
INNER JOIN (
    SELECT from, to, min(price) [price]
    FROM airports 
    GROUP BY from, to) sub
    ON sub.from = a.from
   AND sub.to = a.to
   AND sub.price = a.price

哪能找到匹配的记录。