我有一个mysql数据库,自2004年以来大约有450万行天气数据。我试图找出一段时间内温度等于或低于0的天数。下面是一个数据示例(比温度更多的列)每分钟收集一次数据。我意识到我的日期和时间列应该在一个日期时间列中,我现在使用它,但它只有最近几个月的数据。
date time temperature
2014-02-01 23:58:00 -20.3
2014-02-01 23:59:00 -20.4
--- --- ---
2014-02-02 00:00:00 -20.5
2014-02-02 00:01:00 -20.5
2014-02-02 00:02:00 -20.6
--- --- ---
2014-02-17 08:30:00 17.2
2014-02-17 08:31:00 17.2
我可以单独显示一个月的日子:
的MySQL>选择distinct(日期)作为Ddate,时间作为Ttime,温度作为来自wx_data的Temp其中Year(日期)='2013'和月(日期)='12'和温度< ='0'按日(日期)顺序按日(日期)asc;
+------------+----------+-------+
| Ddate | Ttime | Temp |
+------------+----------+-------+
| 2013-12-05 | 23:59:00 | -3.6 |
| 2013-12-06 | 23:59:00 | -22.7 |
| 2013-12-07 | 23:59:00 | -25.2 |
| 2013-12-08 | 23:59:00 | -4 |
---------------------------------
+------------+----------+-------+
25 rows in set (6.95 sec)
以下不起作用,因为它只显示1月份的数据而2月份的数据(截至今天2月17日)。
的MySQL>选择distinct(日期)作为Ddate,时间作为Ttime,温度作为来自wx_data的Temp,其中Year(date)='2014',温度< ='0'group by day(date)order by day(date)asc;
+------------+----------+-------+
| Ddate | Ttime | Temp |
+------------+----------+-------+
| 2014-01-01 | 00:00:00 | -20.7 |
| 2014-01-02 | 00:00:00 | -28.8 |
| 2014-01-03 | 00:00:00 | -12.5 |
| 2014-01-04 | 08:39:00 | 0 |
| 2014-01-05 | 00:00:00 | -19.8 |
---------------------------------
| 2014-01-31 | 00:00:00 | -21.5 |
+------------+----------+-------+
28 rows in set (6.86 sec)
为了获得二月份,我需要使用当前月份进行另一次选择。因此,虽然我可以手动添加总行数(12月和1月为53),但我仍然需要为2月做另一个选择,并在那些日子中添加总共68天。我只想计算时间跨度的天数,而不是总行数。
有些事情:
从wx_data中选择count_number_of_days,其中温度<= 0;
我希望这是有道理的。
答案 0 :(得分:1)
您不想使用day()
功能。这将返回该月的某一天。你想要date()
:
select date(date) as Ddate, time as Ttime, temperature as Temp
from wx_data
where Year(date) = 2014 and temperature <= 0
group by date(date)
order by date(date)
我假设您的温度存储为数字,因此我删除了单引号。函数year()
返回一个数字,因此“2014”也不应该有单引号。
实际上,您的日期只是没有时间的日期,所以您可以这样做:
select date as Ddate, time as Ttime, temperature as Temp
from wx_data
where Year(date) = 2014 and temperature <= 0
group by date
order by date
请注意,这将从任意匹配的行返回time
和temperature
的值。目前还不清楚你对这些专栏的真正需求。
如果您希望此类天数删除最终group by
并将其转换为聚合查询:
select count(distinct date)
from wx_data
where Year(date) = 2014 and temperature <= 0;
如果您想要两个日期之间的数字,请使用以下内容:
where date >= '2014-01-01' and date < '2015-01-01'
答案 1 :(得分:0)
如果您只想查找指定时间范围内零日以下的天数,那么您可以使用以下内容(SQL Fiddle):
SELECT COUNT(*)
FROM
(
SELECT DISTINCT m.date
FROM MyTable AS m
WHERE m.temperature < 0
AND Year(m.date) = 2014
) AS mm
在示例SQL Fiddle中,有一天中有多个温度读数的独特日子。如果这些读数中的任何一个低于零,那么它将被计算在内。正如您所看到的,有四个独特的日子,其中只有三个低于零。