【问题标题】:MySql: order by before group byMySql:在分组之前排序
【发布时间】:2015-12-16 14:02:25
【问题描述】:

我想在分组之前订购一个子查询。问题是子查询是有序的,就好像我们把它当作查询一样。但是作为子查询 order by 什么都不做。

这是查询:

SELECT * FROM (
SELECT 
    a.id,
    citypair,
    a.season,
    airline,
    class,
    fare,
    rbd,
    season_from,
    season_to,
    schedule_id,
    cp.departure_id,
    cp.destination_id,
    sch.date_time
FROM tarifftool_price_log as a
JOIN tarifftool_seasons as b ON a.seasonId = b.id
JOIN tarifftool_citypairs as cp ON citypair = cp.id
JOIN tarifftool_schedule_queue AS sch ON schedule_id = sch.id
 WHERE       b.date = '12/26' AND class = 'b' ORDER BY schedule_id DESC) as qq 
GROUP BY citypair, airline 

现在我只是想得到一个有序的查询。如果我做到了这一点,我对数据进行分组就没有问题了。

【问题讨论】:

  • 在外部查询中放置 ORDER-BY 子句有什么问题?
  • 添加到@Ctx:sub 中的 Order By 没有任何效果。将 Order By 视为输出的最终格式,而子查询仅限制主查询要考虑的行数。祝你好运。
  • 因为我以后需要使用 group by。下单后无法分组
  • 但是可以分组后下单。请说明你想如何分组
  • GROUP BY citypair, airline 表示您希望每个城市对和航空公司有一个结果行。这与数据的顺序无关。那么你真正想要达到什么目的呢?您确实知道,只要您不指定聚合函数(例如 SUM(fare)MAX(season_from)),您选择的除了 citypair 和航空公司之外的每一列都会从所有匹配项中任意选择,是吗?

标签: mysql group-by subquery sql-order-by grouping


【解决方案1】:

在子查询中使用 Row_Number ROW_NUMBER() OVER(ORDER BY schedule_id)

SELECT * FROM (
SELECT 
ROW_NUMBER() OVER(ORDER BY schedule_id DESC ) as RowId,
a.id,
citypair,
a.season,
airline,
class,
fare,
rbd,
season_from,
season_to,
schedule_id,
cp.departure_id,
cp.destination_id,
sch.date_time
FROM tarifftool_price_log as a
JOIN tarifftool_seasons as b ON a.seasonId = b.id
JOIN tarifftool_citypairs as cp ON citypair = cp.id
JOIN tarifftool_schedule_queue AS sch ON schedule_id = sch.id
WHERE       b.date = '12/26' AND class = 'b'  ) as qq 
GROUP BY citypair, airline 

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 2012-09-19
    • 2014-11-05
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多