在SQL内部联接中使用别名

时间:2014-08-27 15:41:08

标签: mysql sql

我已经看过一些使用连接来获取组中最高值的示例,但我尝试过的方法不喜欢在内连接之外使用别名。

SELECT f.year, f.name, f.date_start, f.date_end, f.max_year FROM ( SELECT EXTRACT(year FROM date_start) AS year, MAX(DATEDIFF(date_end,date_start)) AS max_year FROM mytable GROUP BY year ) AS x inner join mytable AS f on f.year = x.year and f.max_year = x.max_year;

所以,如果我有一张桌子:

Name date_start date_end John 1950-04-05 1960-07-08 Jack 1950-04-06 1960-12-31 Mark 1954-01-01 1970-01-01 Jane 1954-10-10 1978-10-01

然后我希望它为start_date的每一年提出两个日期之间差距最大的条目:

Year Name date_start date_end max_year 1950 Jack 1950-04-06 1960-12-31 3922 1954 Jane 1954-10-10 1978-10-01 8758

有关如何解决这个问题的任何建议吗?

2 个答案:

答案 0 :(得分:1)

看起来你在SELECT列表中使用了错误的别名,这应该更好:

SELECT x.year, f.name, f.date_start, f.date_end, x.max_year FROM
(
    SELECT 
      EXTRACT(year FROM date_start) AS year, 
      MAX(DATEDIFF(date_end,date_start)) AS max_year
    FROM mytable GROUP BY year
)  AS x inner join
mytable AS f on  EXTRACT(year FROM f.date_start) = x.year 
AND DATEDIFF(f.date_end, f.date_start) = x.max_year;

但是,我会这样做:

SELECT name, date_start, date_end
FROM mytable f
WHERE NOT EXISTS (
  SELECT * FROM mytable 
  WHERE  
    EXTRACT(year FROM date_start) = EXTRACT(year FROM f.date_start) AND
    DATEDIFF(date_end, date_start) > DATEDIFF(f.date_end, f.date_start)
)

答案 1 :(得分:1)

你可以试试这个:

SELECT * FROM
(
  SELECT *, EXTRACT(year FROM date_start) AS year, DATEDIFF(date_end,date_start) AS diff
  FROM mytable
  ORDER BY diff DESC
) sq
GROUP BY year
ORDER BY year ASC

小提琴演示:http://sqlfiddle.com/#!2/4d0da/11