我有两个不同的表
bills
billId | bar | drinker | date | time
0001 | SomeBar | Jon Doe | 11-13-18 | 08:10
0002 | SomeBar | Jane Doe| 11-10-18 | 10:10
0003 | twoBar | Mike Doe| 11-11-18 | 12:12
transactions
billID | item | quantity
0001 | bud | 3
0002 | bud | 3
0003 | coors| 1
一个酒吧出售的啤酒总数如何相加?我知道我可以使用内部联接,因为它们都共享一个billId,并且我理解此查询来计算单个表的总数将是这样的。
SELECT item, SUM(quantity) AS TotalQuantity
FROM transactions
GROUP BY item
ORDER BY SUM(quantity) DESC;
Select * FROM bills inner JOIN transactions ON bills.billId = transactions.billID AND bar = SOMEBAR;
答案 0 :(得分:1)
您已经接近了,但是您应该使用GROUP BY
语句对要分组的变量进行分组:
SELECT b.bar, sum(t.quantity) as total
FROM bills b INNER JOIN transactions t ON b.billId = t.billId
GROUP BY b.bar;
答案 1 :(得分:0)
您可以像这样加入bills
表并按bar
分组:
SELECT bar, SUM(quantity)
FROM transactions t
JOIN bills b USING (billID)
GROUP BY b.bar;