在另一列上进行GROUPING时,同时选择MIN和MAX

时间:2015-09-20 09:44:27

标签: mysql sql

我好几天都遇到了以下问题。 我的基表看起来像这样:

departure; departure_date; destination; entered_on

FRA; 2015-10-01; SIN; 2015-09-18 06:24:31

SIN; 2015-10-02; SYD; 2015-09-18 06:24:31

FRA; 2015-10-01; HKG; 2015-09-18 06:28:44  

HKG; 2015-10-04; SYD; 2015-09-18 06:28:44  

SYD; 2015-10-06; LAX; 2015-09-18 06:28:44  

我要做的是获取最小出发日期和最长出发日期目的地的出发,按“entered_on”日期分组。 结果如下:

departure; destination; entered_on

FRA; SYD; 2015-09-18 06:24:31

FRA; LAX; 2015-09-18 06:28:44

我尝试过无数的子查询变种,但都失败了。 大多数时候我做了类似的事情:

SELECT *,
  (SELECT departure 
   FROM table 
   WHERE departure_date = (SELECT MAX(departure_date) FROM table)
  ) AS maxdep 
FROM `table`

但这并没有给我想要的结果。 这甚至可能还是我在这里走错了路?

好的我已经添加了这个结构:fiddle

所以这意味着最初发布的表是通过子查询创建的。

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

SELECT
  SUBSTRING_INDEX(GROUP_CONCAT(t.departure ORDER BY departure_date), ",", "1") AS departure,
  SUBSTRING_INDEX(GROUP_CONCAT(t.destination ORDER BY departure_date DESC), ",", "-1") AS destination,
  t.entered_on
FROM tableName AS t
GROUP BY t.entered_on
  

修改1:order by内添加了group concat,如 @dnoeth 所指出的那样   评价。

这是SQLFIDDLE

  

编辑2:我发布的原始表是通过以下方式创建的:SELECT *,(SELECT created_on FROM created WHERE created.flight_id = flights.id)AS   created_on FROM flights,因此created_on列不是orignially   表的一部分。我尝试将此整个查询放在子查询中   你的“来自”

SELECT
  SUBSTRING_INDEX(GROUP_CONCAT(f.departure ORDER BY f.departure_date ), ",", 1) AS departure,
  SUBSTRING_INDEX(GROUP_CONCAT(f.destination ORDER BY f.departure_date DESC), ",", 1) AS destination,
  c.created_on
FROM flights AS f
  INNER JOIN created AS c ON f.id = c.flight_id
GROUP BY c.created_on

这是New FIDDLE

答案 1 :(得分:1)

我的查询目的并不是很清楚,但你可以从查询开始:

SELECT
  entered_on,
  MIN(departure_date) AS min_date,
  MAX(departure_date) AS max_date
FROM
  yourtable
GROUP BY
  entered_on

然后,您可以使用两个不同的别名将此查询的结果与表一起加回两次:

SELECT
  t1.departure,
  t2.destination,
  d.entered_on
FROM (
  SELECT
    entered_on,
    MIN(departure_date) AS min_date,
    MAX(departure_date) AS max_date
  FROM
    yourtable
  GROUP BY
    entered_on
  ) AS d INNER JOIN yourtable t1
  ON d.entered_on = t1.entered_on AND d.min_date = t1.departure_date
  INNER JOIN yourtable t2
  ON d.entered_on = t2.entered_on AND d.max_date = t2.departure_date

请查看小提琴here

答案 2 :(得分:1)

在大多数其他DBMS中,对于目标,这将是一个简单的FIRST_VALUE(departure) OVER (PARTITION BY entered_on ORDER BY departure_date和类似的LAST_VALUE,但MySQL不支持那些窗口化聚合函数。

你可能会使用一个老技巧:Concat第二列到第一列

select *,
   concat(departure_date, departure),
   concat(departure_date, destination)
from tab;

然后在组合列上执行MAX / MIN,最后使用SUBSTRING提取第2列:

select entered_on,
   substring(min(concat(departure_date, departure)) from 11),
   substring(max(concat(departure_date, destination)) from 11)
from tab
group by entered_on

fiddle