使用逻辑语句创建视图

时间:2014-02-05 10:07:20

标签: oracle toad

我正在使用Toad 10开发Oracle。我想从5个不同的表创建一个视图。它还将包括视图中最终数据的一些计算(添加数量)。我该如何创建它。我很容易使用.net代码,但由于性能原因,我决定使用View或Package来完成。我不擅长数据库,我希望得到任何帮助。

通常我会看到来自一个或两个表的视图,我可以这样做。

我将尝试简单介绍一下我想要实现的目标:

假设我有7个表。

  • 人 - 提供个人信息
  • Apple - 给出苹果销量
  • 橙色 - 给出了橙子的数量
  • 葡萄 - 给出的葡萄数量
  • 柠檬 - 给出了柠檬的销量
  • 樱桃 - 给出樱桃的数量
  • 其他 - 给出其他商品的数量

我想要每个人销售的每件商品的总数。 Required output

现在,在这里我没有Others列,而不是其他表中的每个项目都应该基于Others表中的类别id列添加到任何水果中。例如,其他具有类别ID 1的项目应添加Apple,类别ID为2的项目应添加到Orange等。

我如何获取人员ID 1的数据。

2 个答案:

答案 0 :(得分:1)

with l_pers as (select personid 
                from person
                where personid = 1)
,    l_apple as (select sum(quantity) qt
                 from apple 
                 join l_pers on (l_pers.personid = apple.personid))
,    l_orange as (select sum(quantity) qt
                  from orange 
                  join l_pers on (l_pers.personid = orange.personid))
,    o_others as (select sum(decode(category,1,quantity,0)) appleqt     
                  ,      sum(decode(category,2,quantity,0)) orangeqt
                  from others 
                  join l_pers on (l_pers.personid = others.personid))
select l_pers.personid as personid
,      l_apple.qt + o_others.appleqt as apples
,      l_orange.qt + o_others.orangeqt as orange
from l_pers
,    l_apple
,    l_orange
,    o_others;

答案 1 :(得分:0)

尝试类似

的内容
select
  id                 person_id,
  sum(apple .amount) apple,
  sum(orange.amount) orange,
  sum(grape .amount) grape,
  sum(lemon .amount) lemon,
  sum(cherry.amount) cherry,
  sum(others.amount) others
from
  person             left join 
  apple   using (id) left join
  orange  using (id) left join
  grape   using (id) left join
  lemon   using (id) left join
  cherry  using (id) left join
  others  using (id)
where
  id = 1
group by id;

另见this sql fiddle