请协助以下事项: 我在数据库INFO中有2个表PurchaseO和SalesO。
购买O:
ITEMNO DATE QTY
A 20180701 5
A 20180702 2
A 20180703 1
B 20180701 2
C 20180704 3
SalesO:
ITEMNO DATE QTY
A 20180701 5
A 20180704 4
B 20180702 2
C 20180704 3
如何在DATE之前将这两个表联接起来以获得以下结果:
ITEMNO DATE PurchaseQTY SalesQTY
A 20180701 5 5
A 20180702 2
A 20180703 1
A 20180704 4
B 20180701 2
B 20180702 2
C 20180704 3 3
答案 0 :(得分:3)
一种方法是full join
:
select coalesce(p.itemno, s.itemno) as itemno,
coalesce(p.date, s.date) as date,
p.qty as purchase_qty,
s.qty as sales_qty
from purchases p full join
sales s
on p.itemno = s.itemno and p.date = s.date;
如果任一表中给定项目的日期都有重复,并且您想累加数量,那么union all
/ group by
是更好的方法:
select itemno, date,
sum(purchase_qty) as purchase_qty,
sum(sales_qty) as sales_qty
from ((select p.itemno, p.date, sum(p.qty) as purchase_qty, 0 as sales_qty
from purchases p
group by p.itemno, p.date
) union all
(select s.itemno, s.date, 0, sum(s.qty) as sales_qty
from purchases p
group by p.itemno, p.date
)
) sp
group by itemno, date;
答案 1 :(得分:0)
您可以像加入ID一样加入日期
SELECT
po.ITEMNO,
so.[DATE],
po.QTY AS [PurchaseQTY],
so.QTY AS [SalesQTY]
FROM
PurchasesO AS po
FULL JOIN
SalesO AS so
ON
so.ITEMNO = po.ITEMNO AND
so.[DATE] = po.[DATE]