我有两张桌子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 C. fruit_id fruit 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 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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