我设法按时间汇总一个值,给出一个像这样的查询结果:
SELECT date(takenat) AS takendate,
hour(takenat) AS HourTaken,
avg(reading) AS ch1av
FROM readings
WHERE channelid = 4
GROUP BY takendate, HourTaken
ORDER BY takenat, HourTaken
一些示例输出:
takendate HourTaken ch1av
2013-01-01 0 105.5082
2013-01-01 1 107.2167
2013-01-01 2 106.4833
2013-01-01 3 107.0333
但是,我希望多个channelid的结果(在同一个查询中)
takedate HourTaken ch1av ch2av ch4av
因此,例如channelid的每小时平均值= 1,2和4
我接受了子查询,但我的sql foo还不够!
答案 0 :(得分:2)
使用IN
select date(takenat) AS takendate,
hour(takenat) AS HourTaken,
avg(reading) AS ch1av,
channelid
from readings
where channelid IN (1,2,4)
group by takendate, HourTaken, channelid
order by takenat, HourTaken
这与使用OR
select date(takenat) AS takendate,
hour(takenat) AS HourTaken,
avg(reading) AS ch1av,
channelid
from readings
where channelid = 1 OR
channelid = 2 OR
channelid = 4
group by takendate, HourTaken, channelid
order by takenat, HourTaken
答案 1 :(得分:1)
听起来你想要这样的东西:
SELECT DATE(takenat) AS takendate,
HOUR(takenat) AS HourTaken,
AVG(CASE WHEN channelid = 1 THEN reading ELSE null END) AS ch1av,
AVG(CASE WHEN channelid = 2 THEN reading ELSE null END) AS ch2av,
AVG(CASE WHEN channelid = 4 THEN reading ELSE null END) AS ch4av
FROM readings
WHERE channelid IN (1,2,4)
GROUP BY takendate, HourTaken
ORDER BY takenat, HourTaken