合并两个选择查询并删除重复的列并添加总计

时间:2019-04-07 07:12:45

标签: sql oracle

我尝试将两个选择查询组合在一起,但是我不知道如何删除重复的列类型并求和。我试图将line1更改为:

select t1.genre, t1.film_num, t2.rent_times from

但是Oracle将在t2.rent_times处显示错误“无效标识符”。

select * 
from
    (select 
         genre, count(inventory.film_id) as "film_num"
     from 
         film 
     join 
         inventory using (catalog_num) 
     group by 
         genre) t1
left join
    (select 
         genre, count(rented_item.rental_Num) as "rent_times"
     from 
         film 
     join 
         inventory using (catalog_num)
     join 
         rented_item using(film_id)
     group by 
         genre) t2 on t1.genre = t2.genre;

结果:

GENRE                       film_num GENRE                      rent_times
------------------------- ---------- ------------------------- ----------
Comedy                             3 Comedy                             3
Sci-Fi                            20 Sci-Fi                             8
Action and Adventure              32 Action and Adventure              15
Children and Family                8 Children and Family                5

我希望它看起来像这样:

    GENRE                     film_num    rent_times
    ------------------------- ----------  ----------
    Comedy                             3   3
    Sci-Fi                            20   8
    Action and Adventure              32  15
    Children and Family                8   5  
    Total                                 31 

3 个答案:

答案 0 :(得分:0)

//您可以尝试这样。.我不清楚您的桌子 1.首先

Create table #tblfinal(genre nvarchar(200),filmnum int,renttime int)

insert into #tblfinal(genre,filnum,renttime)
select genre, count(film_id),0
from film  group by genre union all
select genre,0, count(rented_item.rental_Num)
from  rented_item group by genre

select genre,filnum,renttime  from #tblfinal  union all
select 'Total',0,(select sum(renttime) from #tblfinal)

答案 1 :(得分:0)

您可以使用并集添加更多结果,并且可以避免使用具有常见表表达式的临时表

with
t1 as
(select genre
      , count(inventory.film_id) as film_num
 from      film 
      join inventory using (catalog_num) 
 group by genre
)
, t2 as
(select genre
      , count(rented_item.rental_Num) as rent_times
 from      film 
      join inventory using (catalog_num)
      join rented_item using(film_id)
 group by genre
)
, t3 as
(select t1.genre
      , t1.film_num
      , t2.rent_times 
 from           t1
      left join t2 on t1.genre=t2.genre
)

select * from t3
union all
select 'Total' as genre
     , 0 as film_num
     , sum(rent_times) as rent_times
from t3

答案 2 :(得分:0)

您的问题的答案是删除双引号。转义标识符只会使事情变得更加复杂。

您可以使用窗口功能简化查询。我建议:

select f.genre, i.num_films, count(*) as rent_times
from film join
     (select i.catalog_num,
             count(*) over (partition by catalog_num) as num_films
      from inventory
     ) i
     using (catalog_num) join
     rented_item
     using (film_id)
group by genre, i.num_films;