我有以下的SQL:
with CTE as (
select user_id,level,plugged,plugged_ac,plugged_usb,created_at from probe_batteries where probe_batteries.user_id='91' and probe_batteries.created_at > timestamp '2014-06-07 17:00:00'
and probe_batteries.created_at < timestamp '2014-06-07 23:00:00'
)
select CTE.user_id as user_id, avg(CTE.level), bool_or(CTE.plugged), bool_or(CTE.plugged_ac), bool_or(CTE.plugged_usb),date_trunc('second',CTE.created_at) as created_at
from CTE
group by created_at, user_id
order by created_at asc
但表结果不会根据created_at聚合(参见结果中的最后一列),这是时间戳类型
91;95.0000000000000000;f;f;f;"2014-06-07 20:46:06"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:11"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:12"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:12"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:12"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:13"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:13"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:13"
91;95.0000000000000000;f;f;f;"2014-06-07 21:19:14"
我的sql句子有什么问题吗? THX
答案 0 :(得分:0)
您的表达别名created_at
与您的CTE
命名子查询的列名相匹配。
尝试给出另一个别名,例如:
WITH CTE AS (
SELECT user_id,level,plugged,plugged_ac,plugged_usb,created_at
FROM probe_batteries
WHERE user_id='91' AND created_at > timestamp '2014-06-07 17:00:00'
AND created_at < timestamp '2014-06-07 23:00:00'
)
SELECT CTE.user_id as user_id, avg(CTE.level), bool_or(CTE.plugged),
bool_or(CTE.plugged_ac), bool_or(CTE.plugged_usb),
date_trunc('second',CTE.created_at) AS dt_at
FROM CTE
GROUP BY dt_at, user_id
ORDER BY dt_at ASC;