1

我有一个 select 语句,它给出了一个时间范围内的活动。例如

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

为此,我正在考虑确定行操作的不同值,然后将其与同一个表连接起来。这在 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 万个条目)。

提前致谢!

4

2 回答 2

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;

小提琴:http ://sqlfiddle.com/#!4/27a40/1

于 2013-03-08T15:58:12.397 回答
1

您需要在内部查询中添加 group by 并在 distinct 周围删除 ()。这对我有用 - 类似于您的查询,但不包括计数:

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 
/
于 2013-03-08T15:48:25.610 回答