2013-03-08 130 views
1

我有一个select语句,它给出了时间范围内的活动。例如。Oracle SQL:在LEFT JOIN的t2中使用distinct(t1.field)

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 

但如果我这样做,我understandibly得到错误的表t2不是t1的select语句内有效。

请帮助我完成任务。但我不想在原始表格上做独特的事情(它有五千万条记录)。

在此先感谢!

+0

您可以在时间欺骗:他们'从0到23,而不是通过表格,你可以做'...从(SELECT LEVEL-1 AS小时从双连接到LEVEL <= 24)'。另外,您是否有Action的查找表?如果是这样,你可以通过查找表将上面的小黑客交叉加入,并且有一个完整的小时/动作网格,而无需靠近5000万行表。 – 2013-03-08 15:54:51

+0

独特是***不是***功能。 'distinct(t2.action)'完全没用。它与'distinct t2.action'完全相同。你不写'select(t2.action)...',不是吗? – 2013-03-08 17:12:20

回答

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

+0

你可以为它创建一个小提琴吗?你可以从[这里](http://sqlfiddle.com/#!4/d41d8/8604) – 2013-03-08 16:15:42

+0

@FlorinGhita没有prob..added。 – DazzaL 2013-03-08 17:10:35

1

您需要在您的内部查询中添加group by,并将distinct()围绕remove()添加。这对我的作品 - 类似查询仅瓦特/计数:

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 
/
+1

你的例子(让我想起我的代码)为JOIN使用唯一键。 OP的表没有他们。这根本没有帮助。 – 2013-03-08 15:59:30

+0

@PM 77-1 - 是的,我一直在学习和重用其他人的例子。它与......一样加入t1.action = t2.action。我不认为这个关键与这个特定案例有关。问题是关于不同的。但无论如何,让OP决定。 – Art 2013-03-08 16:25:50