我有两个表:Issue
和Return
。两个表都有article_id
,person_id
和quantity
列。我需要从Return
表中为一个人减去Issue
表,并按结果名称对结果进行分组。
首先选择如下:
SELECT Article.Name, SUM(Issue.Quantity)
FROM Issue LEFT JOIN Article ON (Issue.ArticleID = Article.ID)
WHERE Issue.PersonID = 2
GROUP BY Article.Name
ArticleName | Quantity ------------------------ Shoes | 5 Coats | 3 Hats | 3
第二个像这样:
SELECT Article.Name, SUM(Return.Quantity)
FROM Return LEFT JOIN Article ON (Return.ArticleID = Article.ID)
WHERE Return.PersonID = 2
GROUP BY Article.Name
ArticleName | Quantity ------------------------ Shoes | 3 Coats | 2 Hats | 0
问题是,如何从第一个(Return
- Issue
)中减去第二个选择以获得这样的表:
ArticleName | Quantity ------------------------ Shoes | 2 Coats | 1 Hats | 3
最终结果中的数量应该是要退回的剩余物品的数量。
答案 0 :(得分:4)
这可能有效:
(经过大量编辑 - 我的第一个答案没有机会工作......)
SELECT Article.Name
, (SELECT SUM(Issue.Quantity) FROM Issue WHERE Issue.ArticleID = Article.ID AND Issue.PersonID = 2)
- (SELECT SUM(Return.Quantity) FROM Return WHERE Return.ArticleID = Article.ID AND Return.PersonID = 2)
FROM Article