我有以下sql-query:
SELECT DATE(time), ROUND(AVG(out_temp),2)
FROM data_table
WHERE id= 1 AND time BETWEEN '2012-08-18' AND '2012-08-30'
GROUP BY DATE(time)
ORDER BY time ASC
返回:
date avg_temp
2012-08-18 11.41
2012-08-19 5.90
2012-08-28 11.22
2012-08-29 10.07
到目前为止一切运作良好......但我想添加具有常数值的缺失日期:
date avg_temp
2012-08-18 11.41
2012-08-19 5.90
2012-08-20 <value>
... ...
2012-08-27 <value>
2012-08-28 11.22
2012-08-29 10.07
我该如何修改查询?有人可以帮我解决这个问题吗?我阅读了一些关于使用预填充日期值创建单独日历表的帖子,但我仍然没有让它工作。
答案 0 :(得分:1)
如果您的数据表实际上每个日期都有数据,您可以这样做:
SELECT thedate, coalesce(ROUND(AVG(out_temp),2), <value>)
FROM (select distinct date(time) as thedate
from data_table
) dates left outer join
data_table dt
on date(time) = thedates.date
WHERE id= 1 AND thedate BETWEEN '2012-08-18' AND '2012-08-30'
GROUP BY thedate
ORDER BY time ASC
您需要的是一张能够生成所需日期的驾驶表。然后,您可以离开加入此表,以获得所需的摘要。 COALESCE功能可让您输入默认值。
答案 1 :(得分:1)
创建一个包含所需日期的表格,然后执行LEFT JOIN。 E.g。
CREATE TABLE calendar ( day DATE PRIMARY KEY );
然后插入表中,可能是你的编程语言循环(伪代码):
for day in day_range( start_date, end_date ):
query( 'INSERT INTO calendar VALUES ( ' + day + ' );' );
然后进行LEFT JOIN:
SELECT DATE(day), ROUND(AVG(out_temp),2)
FROM data_table LEFT JOIN calendar ON data_table.time = calendar.day
WHERE id= 1 AND day BETWEEN '2012-08-18' AND '2012-08-30'
GROUP BY DATE(day)
ORDER BY day ASC