考虑到我有下表
WindDirection | WindSpeed | Date
W | 12 | 17/01/14
NNW | 20 | 20/02/14
SE | 15 | 30/04/14
ENE | 25 | 21/06/15
NNE | 23 | 10/12/15
WSW | 8 | 07/01/15
S | 19 | 05/06/15
我如何获得每年的最高金额? 我想要实现这个
Year | WindSpeed | WindDirection
2014 | 20 | NNW
2015 | 25 | ENE
这是我的查询,它不起作用,只是让你有了一个想法
SELECT CONCAT("20", SUBSTRING(`Date`, -2)) AS `Year`, `WindSpeed`, `WindDirection`
FROM `weather`
WHERE `WindSpeed` = (SELECT MAX(`WindSpeed`)
FROM `weather`)
GROUP BY `Year` DESC
提前致谢!
答案 0 :(得分:2)
你很亲密。有多种方法可以执行此操作,但对查询的简单修订是使用相关子查询:
SELECT CONCAT('20', RIGHT(`Date`, 2)) AS `Year`, `WindSpeed`,
`WindDirection`
FROM `weather` w
WHERE w.WindSpeed = (SELECT MAX(w2.WindSpeed)
FROM weather w2
WHERE RIGHT(w2.`Date`, 2) = RIGHT(w.`Date`, 2)
)
GROUP BY `Year` DESC;
注意:您似乎将日期存储为字符串。您不应该这样做,因为MySQL提供了正确的日期/日期时间数据类型。如果它存储为date
,请使用year()
函数而不是字符串操作。
答案 1 :(得分:2)
您可以使用以下查询
SELECT B.Year ,
WindSpeed ,
A.WindDirection
FROM weather A
INNER JOIN ( SELECT YEAR ,
MAX(WindSpeed) AS WindSpeed
FROM ( SELECT YEAR(Date) AS YEAR ,
WindSpeed ,
WindDirection
FROM weather
) A
GROUP BY YEAR
) b ON A.WindSpeed = b.WindSpeed
AND B.YEAR = YEAR(A.Date)