我有一个选择陈述
SELECT MAX(windspeed) as maxwind, count(if (avgspeed<0.8, avgspeed,0)) as no_cases
from towerdata
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
我想获得windspeed等于maxwind的'datetime'值。如何构建sql?
我的目的是获得最大风速的值,以及在此速度下风吹的时间。当风速小于0.8米/秒时也没有。我可以使用两个单独的select语句,但想减少行
答案 0 :(得分:0)
按windspeed
排序并仅拍摄第一张唱片
SELECT datetime
from towerdata
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
order by windspeed desc
limit 1
答案 1 :(得分:0)
这是一种方法,使用where
子句中的子查询:
select max(windspeed) as max_windspeed, count(*)
from towerdata td
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00' and
windspeed = (select max(windspeed) as maxws
from towerdata
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
)
编辑:
我意识到你想要一个单独的计数,所以使用一个连接:
select max(td.maxws) as max_windspeed,
max(case when td.windspeed = td.maxws then td.datetime end) as maxws_datetime,
sum(case when td.avgspeed < 0.8 then td.avgspeed else 0 end)
from towerdata td left outer join
(select max(windspeed) as maxws
from towerdata
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00'
) tdmax
on td.windspeed = tdmax.windspeed
where datetime between '2013-01-01 00:00:00' and '2013-01-01 23:00:00';
顺便说一下,表达式:
count(if (avgspeed<0.8, avgspeed,0))
可能没有做你想要的。它会计算行数,与count(*)
相同。 count()
返回非NULL值的数量。这就是为什么我用case
替换它。