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;
Create view using logical statement
문제
I am working on Oracle using Toad 10. I want to create a view from 5 different tables. It will include some computations as well(addition of quantities) for the final data in view. How can I create it. Its easy for me to do in .net code, however due to performance reason it was decided to do it using a View or a Package. I am not good at database and I would appreciate any kind of help.
Usually I see views from one or 2 tables joined which I can do.
I will try to give a simple scenario of what I am trying to achieve:
Suppose I have 7 tables.
- Person - Gives personal information
- Apple - Gives count of apple sold
- Orange - Gives count of oranges sold
- Grape - Gives count of grapes sold
- Lemon - Gives count of lemon sold
- Cherry - Gives count of cherry sold
- Others - Gives count of other items sold
I want an ouput of the total number of each items sold by each person.
Now, here I dont have a Others column, instead of that each item in Others table should be added to any of the fruit based on a category id column in Others table. For example, other items with category id 1 should be added Apple, items with category id 2 should be added to Orange etc.
How can I want to get the data for person id 1.
해결책
다른 팁
Try something like
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;
See also this sql fiddle