这是一项家庭作业。我只是简单地不明白该怎么做。
这个特定问题的说明是:
List the branch name for all branches that have at least one
book that has at least 4 copies on hand.
有问题的表格是:
分支机构:
BranchName | BranchId
Henry Downtown | 1
16 Riverview | 2
Henry On The Hill | 3
清单:
BookId | BranchId | OnHand
1 | 1 | 2
2 | 3 | 4
3 | 1 | 8
4 | 3 | 1
5 | 1 | 2
6 | 2 | 3
根据我的理解,我可以通过以下方式获取每个分支名称的OnHand数量:
SELECT BranchName, SUM(OnHand)
FROM Branch B, Inventory I
WHERE B.BranchId = I.BranchId
GROUP BY BranchName;
但是我不知道如何对每个分支的OnHand和4进行比较。
任何帮助都会受到赞赏,伙计们!
答案 0 :(得分:1)
这样的事情(假设同一本书可能在不同的分支中):
SELECT DISTINCT BranchName
FROM Branch B, Inventory I
WHERE B.BranchId = I.BranchId
GROUP BY BranchName, I.BookId
HAVING SUM(onHand) >= 4;
这是你的想法吗?
修改强>
如果广告资料表列出每本书每个分支只有一次,那么我们就可以摆脱bookid
和DISTINCT
子句的分组。
查询变为:
SELECT BranchName
FROM Branch B, Inventory I
WHERE B.BranchId = I.BranchId
GROUP BY BranchName
HAVING SUM(onHand) >= 4;
This SQL Fiddle用于简化查询。