有没有办法在MySQL中总结两列的产品?

时间:2016-12-22 22:00:28

标签: mysql join sum

以下是我的表格:

-- receipts
| id | date       |
|----|------------|
| 1  | 2016-12-20 |
| 2  | 2016-12-20 |
| 3  | 2016-12-21 |

-- purchases
| id | receipt_id | item        | price | tax_rate |
|----|------------|-------------|-------|----------|
| 1  | 1          | apples      |  3.89 | 0.000    |
| 2  | 1          | canned soup |  2.99 | 0.095    |
| 3  | 1          | candy bar   |  0.99 | 0.095    |
| 4  | 2          | gas         | 26.78 | 0.000    |
| 5  | 3          | chips       |  3.99 | 0.095    |
| 6  | 3          | dip         |  2.99 | 0.095    |

我正在尝试执行一个查询,它会从收据表中返回3个项目,包括小计,总税金和总计。到目前为止,这就是我对SQL的看法。

SELECT 
    receipts.id, 
    receipts.date, 
    SUM(purchases.price) AS subtotal, 
    SUM(purchases.price * purchases.tax_rate) AS tax,
    SUM(subtotal + tax_rate)
FROM receipts
RIGHT JOIN purchases ON purchases.receipt_id = receipts.id;

最终结果应如下所示:

| id | date       | subtotal | tax  | total |
|----|------------|----------|------|-------|
| 1  | 2016-12-20 |  7.87    | 0.38 |  8.25 |
| 2  | 2016-12-20 | 26.78    | 0.00 | 26.78 |
| 3  | 2016-12-21 |  6.98    | 0.66 |  7.64 |

3 个答案:

答案 0 :(得分:2)

你快到了。由于您希望聚合结果,因此需要使用聚合函数SUM(已经完成),但是当您使用SUM时,您需要告诉查询您希望如何聚合数据。您可以通过添加按语句分组来执行此操作。

SELECT 
    receipts.id, 
    receipts.date, 
    SUM(purchases.price) AS subtotal, 
    SUM(purchases.price * purchases.tax) AS tax,
    SUM(purchases.price) + SUM(purchases.price * purchases.tax) AS total
FROM receipts
RIGHT JOIN purchases ON purchases.receipt_id = receipts.id;
GROUP BY receipts.id, receipts.date

答案 1 :(得分:1)

第三个SELECT值应为

SUM(purchases.price) + SUM(purchases.price * purchases.tax) AS total

答案 2 :(得分:1)

这似乎是INNER JOIN的情况,您需要GROUP BY receipt_id。其余的看起来很好,除了shmosel回答的内容。

SELECT 
    receipts.id, 
    receipts.date, 
    SUM(purchases.price) AS subtotal, 
    SUM(purchases.price * purchases.tax) AS tax,
    SUM(purchases.price) + SUM(purchases.price * purchases.tax) AS total
FROM receipts
INNER JOIN purchases ON purchases.receipt_id = receipts.id
GROUP BY receipt_id

mysql不知道生成的别名,你需要在每个选择的select子句中编写计算,并希望mysql正确处理它并且不会计算两次。