繁体   English   中英

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

[英]How to retrieve specific columns in a GROUP BY sql statement?

airports

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

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

在以下作品中,BUT仅给出了从价格到价格的3列。 不是整个实体。

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

我将如何适应呢?

通常使用窗口函数完成此操作:

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

要处理“联系”(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;

您可以对结果进行排序,并在每个分组上使用不重复来获取第一个结果

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

上面的查询应该工作

这是一个非常简单的解决方案。 SQLFiddle在这里

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 ...因为您需要整个实体。

如果要获取全部数据,请使用以下查询解决您的问题:

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

接合处仅用于从此处/此处获得每对夫妇的最佳价格。

希望这会帮助你。

无法获得“整个实体”,表中可能有很多行可能包含+到+最小价格的匹配项

例如,如果您的表包含

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行都满足您的价格从+到+最小的标准。

您可以编写查询

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

这将为您提供匹配的记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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