1

我有一张这样的桌子

| customer_id | item_id | price | amount |

我想检索每个客户在单个查询中花费的金额。

我试过了:

SELECT SUM(price * amount) AS total FROM table GROUP BY customer_id

但这会产生天文数字的高值total。它不可能是正确的。

我也试过

SELECT @total := @total + (price * amount) AS total FROM table
CROSS JOIN (SELECT @total := 0) CONST
GROUP BY customer_id

但这并不是从0每个客户开始的,所以以前的总数会叠加......

如何正确检索我想要的数据?

4

4 回答 4

2

您的初始查询是正确的:

SELECT SUM(price * amount) AS total
FROM table
GROUP BY customer_id;

(虽然我会包括customer_idSELECT条款中。)

如果您有“天文数字”,那么问题就出在您的数据上。很可能,问题在于每一行的“价格”实际上是“总计”。

于 2013-09-10T13:14:44.723 回答
1

您必须将客户 ID 添加到您的选择子句中。

于 2013-09-10T13:14:04.463 回答
0

我认为您的查询应该是正确的。我在我的服务器上尝试了以下内容:

create table test (customer_id int, item_id int, price money, amount int)

insert test values (1,1,10,2)
insert test values (1,2,12,4)

insert test values (2,1,10,2)
insert test values (2,3,5,1)
insert test values (2,4,0.5,21)

SELECT customer_id,sum(price*amount) FROM test
GROUP BY customer_id
于 2013-09-10T13:20:12.673 回答
0

我认为你需要这样的东西:

select customer_id,sum(price * amount) from table group by customer_id
于 2013-09-10T13:22:19.277 回答