我有一张桌子,每15分钟就会记录一次降雨量,因此一天的总降雨量是95次记录中“降雨量”的总和。以下查询正确返回日期列表和当天的降雨量。
select thedate as tdate,sum(rain) as dailyrain
from weatherdata
group by year(thedate), month(thedate), day(thedate)
(日期存储为datetime,rain存储为整数)
我现在想把它作为一个子查询并返回最大降雨量的日期。
我的查询正确地返回了最大降雨量,但没有与降雨量相关的正确日期。
select maxdate,max(dailyrain) from (select thedate as maxdate,sum(rain) as dailyrain
from weatherdata
group by year(thedate), month(thedate), day(thedate)) as maxrain
我想我可能不得不使用JOIN。我知道很多类似的问题已在这里得到解答,但是我无法完全掌握这种语法。任何帮助将不胜感激。
答案 0 :(得分:2)
SELECT DATE(thedate) as tdate, sum(rain) as dailyrain
FROM weatherdata
GROUP BY DATE(thedate)
ORDER BY sum(rain) DESC, DATE(thedate) DESC
LIMIT 1 ;
或:
SELECT DATE(thedate) as tdate, sum(rain) as dailyrain
FROM weatherdata
GROUP BY DATE(thedate)
ORDER BY dailyrain DESC, tdate DESC
LIMIT 1 ;
答案 1 :(得分:1)
要获得具有最大降雨量的所有日期:
SELECT DATE(thedate), SUM(rain)
FROM weatherdata
GROUP BY DATE(thedate)
HAVING SUM(rain) = (
SELECT SUM(rain)
FROM weatherdata
GROUP BY DATE(thedate)
ORDER BY SUM(rain) DESC
LIMIT 1
)
答案 2 :(得分:0)
请试试这个
select tdate,dailyrain from
(select date(thedate) as tdate,sum(rain) as dailyrain
from weatherdata
group by date(thedate))r
WHERE dailyrain =
(select max(dailyrain) as maxrain from
(select date(thedate) as tdate,sum(rain) as dailyrain
from weatherdata
group by date(thedate)
)m
)