[英]Using aliases in SQL inner join
I've had a look at a few examples of using joins to get the highest value in a group, but the methods I have tried don't like the use of aliases outside of the inner join. 我看过一些使用联接获得组中最高值的示例,但是我尝试过的方法不喜欢在内部联接之外使用别名。
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;
So if I have a table: 因此,如果我有一张桌子:
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
Then I want it to bring up the entries that have the greatest gap between the two dates, for each year of the start_date: 然后,我希望它针对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
Any suggestions of how to get around this? 关于如何解决这个问题的任何建议?
It looks like you are using wrong aliases in your SELECT list, this should be better: 看起来您在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;
However, I would do it like this: 但是,我会这样做:
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)
)
You can try with this: 您可以尝试以下操作:
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
Fiddle demo: http://sqlfiddle.com/#!2/4d0da/11 小提琴演示: http ://sqlfiddle.com/#!2/4d0da/11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.