我有两张桌子,并且购买它们都具有以下结构
ID, ItemID, Quantity, Date
。我想从装运中获取物品的总数量-购买
第三个表Item中的ID有一个外键,结构为
ID int auto_increment,
ItemCode VARCHAR(10) unique NOT NULL,
ItemDescription VARCHAR(50),
Price decimal(4,2) DEFAULT 0,
primary key(ID)
我曾尝试通过联接来做到这一点,但是由于某些原因,每次我都会获得更多重复数据
答案 0 :(得分:0)
;WITH cte
AS (SELECT SUM(s.Quantity) AS 'shipment sum',
s.ItemId
FROM dbo.Shipment s
GROUP BY s.ItemId)
SELECT c.[shipment sum] - b.[purchase sum] AS 'total quantity',i.ItemDescription
FROM cte AS c
INNER JOIN
(
SELECT SUM(p.quantity) as'purchase sum',
p.itemid
FROM dbo.Purchase p
GROUP BY p.ItemId
) b ON c.itemid = b.itemid
INNER JOIN item i ON i.id=c.itemid
答案 1 :(得分:0)
假设您希望全天总计,按ItemCode排序
select i.ID, i.ItemCode, i.ItemDescription, i.Price, t.Quantity
from Items i
left join (
select ItemID, sum(Quantity) Quantity
from (
select ItemID, Quantity
from Shipment
union all
select ItemID, -Quantity
from Purchase
) t
group by ItemID
) t on t.ItemID = i.ID
order by i.ItemCode;