2013-11-22 51 views
0

我有两个表A和B加入几个条件

date  Fruit_id amount 
date_1   1  5 
date_1   2  1  
date_2   1  2 
.... 

date  Fruit_id amount 
date_1   1  2 
date_1   3  2  
date_2   5  1 
.... 

和id_tableç fruit_id水果 1苹果 ....

我试图得到一个表中显示了每个水果在一定日期内相邻的两张桌子的数量。我试过

SELECT a.date, f.fruit, a.amount as amount_A, b.amount as amount_B 
from table_A a 
JOIN table_C f USING(fruit_id) 
LEFT JOIN table_B b ON a.date = b.date AND a.fruit_id = d.fruit_id 
WHERE a.date ='myDate' 

现在每个水果创建几行而不是1,并且这些值看起来相当随机的数量组合。 我怎样才能得到一个整齐的桌子

date fruit A B 
myDate apple 1 5 
myDate cherry 2 2 
.... 

回答

0

测试这与您的数据,它似乎工作。你想使用一个完整的外部联接,以包括A和B中的所有水果和日期:)

SELECT C.Name 
    , COALESCE(A.Date, B.Date) 
    , COALESCE(A.Amount, 0) 
    , COALESCE(B.Amount, 0) 
    FROM C 
    JOIN (A FULL OUTER JOIN B ON B.FruitID = A.FruitID AND B.Date = A.Date) 
    ON COALESCE(A.FruitID, B.FruitID) = C.FruitID 
ORDER BY 1, 2 
0

尝试

select A.date, C.fruitname, A.amount, B.amount 
from A,B,C 
where 
A.date = B.date 
and A.fruitid = B.fruitid 
and A.fruitid = C.fruitid 
order by A.fruitid 
0
select A.DATE as DATE, 
     A.FRUIT_ID FRUIT, 
     sum(A.AMOUNT) A, 
     sum(B.AMOUNT) B 
    from A,B 
where A.DATE = B.DATE 
    and A.FRUIT_ID = B.FRUIT_ID 
group by A.DATE,A.FRUIT_ID 
order by A.DATE asc 
0

有几种选择,一种是全加入另一个是子查询..由于某种原因,我会做子查询选项。

select x.date, x.fruit_id, 
(select a.amount from a where a.fruit_id=x.fruit_id and a.date=x.date) a, 
(select b.amount from b where b.fruit_id=x.fruit_id and b.date=x.date) b 
from (select a.date,a.fruit_id from a union select b.date, 
b.fruit_id from b) as x 

此外,您可以使用完全加入,虽然我没有oracle来测试此版本,我相信它会工作。

select nvl(a.date,b.date) as date, nvl(a.fruit_id,b.fruit_id) as fruit_id, 
a.amount as a, b.amount as b 
from a full outer join b on b.date=a.date and b.fruit_id=a.fruit_id 
0

我认为你的连接很可能没有返回足够的记录。这其中应该返回所有的水果,在A或B的记录,用相同的金额

SELECT ab.date, f.fruit, ab.amount_A, ab.amount_B 
table_C f 
JOIN (SELECT a.date, 
       COALESCE(a.fruit_id, b.fruit_id) as fruit_id, 
       COALESCE(a.amount, 0) as amount_A, 
       COALESCE(b.amount, 0) as amount_B 
     from table_A a 
     FULL OUTER JOIN table_B b ON a.date = b.date AND a.fruit_id = d.fruit_id 
    ) ab ON f.fruit_id = ab.fruit_id