ITPub博客

首页 > 数据库 > Oracle > SQL解惑二--谜题51解法

SQL解惑二--谜题51解法

原创 Oracle 作者:hu825065235 时间:2014-07-20 20:36:58 0 删除 编辑

SQL解惑二
谜题51:
构建数据SQL:

点击(此处)折叠或打开

  1. create or replace view 预算 (项目 ,种类 ,预算费用)
  2. as
  3. select 1 , 9100 , 100.00 from dual union all
  4. select 2 , 9100 , 15.00 from dual union all
  5. select 3 , 9100 , 6.00 from dual union all
  6. select 4 , 9200 , 8.00 from dual union all
  7. select 5 , 9200 , 11.00 from dual;

  8. create or replace view 支出(收据 ,项目, 支出费用)
  9. as
  10. select 1 , 1 , 10.00 from dual union all
  11. select 2 , 1 , 20.00 from dual union all
  12. select 3 , 1 , 15.00 from dual union all
  13. select 4 , 2 , 32.00 from dual union all
  14. select 5 , 4 , 8.00 from dual union all
  15. select 6 , 5 , 3.00 from dual union all
  16. select 7 , 5 , 4.00 from dual;
实现如下效果:


该类问题应该先聚合,然后再进行表的关联

解答如下:

点击(此处)折叠或打开

  1. select v.种类, v.预算合计, n.支出合计
  2.   from (select y.种类, sum(y.预算费用) as 预算合计
  3.   from 预算 y
  4.  group by y.种类)v
  5.   join
  6.  (select y.种类, sum(支出费用) as 支出合计
  7.     from 预算 y
  8.     join 支出 z
  9.    using (项目)
  10.    group by y.种类) n
  11.     on (v.种类 = n.种类)


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29507357/viewspace-1223203/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-02-26

  • 博文量
    34
  • 访问量
    83414