【问题标题】:Getting total sales data from two tables从两个表中获取总销售额数据
【发布时间】:2019-04-18 23:48:17
【问题描述】:

我有两个不同的表

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;

【问题讨论】:

  • 感谢您包含显示表格结构和示例数据而不是屏幕截图的文本!

标签: mysql


【解决方案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;

【讨论】:

    【解决方案2】:

    您可以像这样加入bills 表并按bar 分组:

    SELECT bar, SUM(quantity)
    FROM transactions t
        JOIN bills b USING (billID)
    GROUP BY b.bar;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多