如何加入两个查询,其中一个查询来自其他查询?

时间:2016-02-12 04:42:18

标签: sql oracle join

有人可以解释我这有什么不对吗?我的查询是这样的......

select t1.year, t1.empid, t2.tcost
from (select year,empid,sum(cost) as total from orders group by year,empid) t1
inner join (select year, max(total) from t1 group by year) t2
on t1.year= t2.year

我收到如下错误消息

ERROR at line 3:

ORA-00942: table or view does not exist

我知道我可以使用WITH子句实现这一点,但我想知道在这种情况下如何使用join。

提前致谢

3 个答案:

答案 0 :(得分:2)

如果在您的查询中使用自联接,通常会有基于分析函数的等效查询。 在大多数情况下,优点是执行时间更短。在这里你可以使用max ... keep dense rank ...

select year, empid, sum_cost 
  from (
    select year, empid, sum(cost) sum_cost,
           max(sum(cost)) keep (dense_rank last order by sum(cost)) 
                          over (partition by year) max_cost
      from orders group by year, empid )
  where sum_cost = max_cost

示例数据和输出:

create table orders (year number(4), empid number(5), cost number(10,2));
insert into orders values (2010, 1, 100);
insert into orders values (2010, 1, 115);
insert into orders values (2010, 1, 207);
insert into orders values (2010, 2, 104);
insert into orders values (2011, 1,  90);
insert into orders values (2011, 2,  15);
insert into orders values (2011, 2, 107);
insert into orders values (2011, 3, 100);

输出:

YEAR  EMPID  SUM_COST
----  -----  --------
2010      1       422
2011      2       122

编辑:如果您想在此处进行自我加入,我怀疑您是否可以取消with条款。特别是在使用两次或更多次复杂子查询时,会使用with。 如果您按照评论中的建议坚持join而不是where (year,tcost) in ...,请使用:

with vvn as (select year, empid, sum(cost) as sc from orders group by year, empid) 
  select v1.year, v1.empid, v1.sc from vvn v1
    join (select year, max(sc) msc from vvn group by year) v2 
      on v1.year = v2.year and v1.sc = v2.msc;
顺便说一下,我的第一个答案的缩短版本并不需要keep dense rank部分,更简单的是:

select year, empid, sum_cost 
  from (select year, empid, sum(cost) sum_cost,
               max(sum(cost)) over (partition by year) max_cost
          from orders group by year, empid )
  where sum_cost = max_cost

somehwat修改版keep...的版本仍然有效且有趣,但您可能已经注意到了这一点。

答案 1 :(得分:0)

getDuration()

你在t1和INNER之间有一个逗号,并且FROM T1中的语法错误,你不能将内部表连接到另一个内部。最大(总)也需要别名。全部如上所示。

答案 2 :(得分:0)

试试这个

select t.year, t.empid, t.total
from (select t1.year,t1.empid,sum(t1.cost) as total from orders as t1  
inner join orders as t2 on t1.year= t2.year  group by t1.year,t1.empid) t

SQL JOINing a Table to Itself