我有一个select语句,可以在一个时间范围内提供活动。 E.g。
Hour | Action | Count
---------------------
00 | a1 | 23
00 | a2 | 48
01 | a1 | 16
02 | null | null
03 | a1 | 5
04 | a2 | 2
你看,由于产生这个结果的分组,没有计算小时01,动作02等等。我想要的是以下内容:
Hour | Action | Count
---------------------
00 | a1 | 23
00 | a2 | 48
01 | a1 | 16
01 | a2 | 0
02 | a1 | 0
02 | a2 | 0
03 | a1 | 5
03 | a2 | 0
04 | a1 | 0
04 | a2 | 2
为此,我正在考虑确定行Action的不同值,然后将其与同一个表连接起来。这在SQL代码中就是这样的:
select distinct(t2.action) as action
from t2 as t1
left join (select hour, action, count from <whatever to get the table>) as t2
on t1.action = t2.action
但如果我这样做,我可以理解地得到表t2在t1的select语句中无效的错误。
请帮我完成任务。但是我不想在原始表上做出明显的(它有5000万个条目)。
提前致谢!
答案 0 :(得分:2)
你可以使用外连接+分区子句:
select hours.hour, t2.action, nvl(t2.count, 0)
from (select distinct hour from t2) hours
left outer join (select * from t2) t2
partition by (t2.action)
on hours.hour = t2.hour
where t2.action is not null
order by hour, action;
或者如果您想生成小时0-23,无论行是否在表/视图中:
with hours as (select to_char(rownum-1, 'fm00') r from dual connect by level <= 24)
select hours.r, t2.action, nvl(t2.count, 0)
from hours
left outer join (select * from t2) t2
partition by (t2.action)
on hours.r = t2.hour
where t2.action is not null
order by r, action;
答案 1 :(得分:1)
您需要在内部查询中添加group by,并在distinct周围删除()。这对我有用 - 类似于你的查询只有w / out计数:
SELECT distinct rm.user_id as user_id -- rm.user_id comes from inner query
FROM Readings r
LEFT JOIN
(
SELECT r2.user_id, r2.reading_time, r2.x, r2.y
FROM Readings r2
) rm
ON rm.user_id=r.user_id
/