2014-08-27 58 views
0

我已經查看了一些使用連接來獲取組中最高值的示例,但我嘗試的方法不喜歡使用內部連接之外的別名。在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

然後,我希望它彈出有兩個日期之間的最大差距的條目,每一年的起始日期爲:

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

任何的如何解決建議 這個?

+0

當您運行查詢或結果與預期不符時,是否收到錯誤消息? – Bulat 2014-08-27 15:45:31

回答

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) 
) 
+0

http://sqlfiddle.com/#!2/4d0da/13 – Bulat 2014-08-27 16:05:05

+0

謝謝@Bulat,兩人工作得非常好!我現在看到我的別名出錯了。我很喜歡使用連接,所以感謝您的幫助! – Andy 2014-08-27 22:42:18

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

+0

+1工作解決方案,但它是MySQL黑客,所以我不會推薦使用它。 – Bulat 2014-08-27 16:11:11