我有一个带有3个表的关系数据库。第一个,Categories
具有蔬菜,肉类,奶酪等商品的类型。第二个,Clients
拥有在商店购买的所有客户。最后一个Cart
与客户端ID,类别ID和客户在商店中花费的金额有关系。
我需要打印一份报告,使用MySQL了解每个客户在一个类别中花了多少钱。报告看起来应该是
+--------+---------+------+---------+
| Client | Veggies | Meat | Cheeses |
+--------+---------+------+---------+
| Tom | 1000 | NULL | 1500 |
| John | NULL | NULL | 2000 |
| Alice | 1000 | 1000 | 1000 |
+--------+---------+------+---------+
现在,我正在使用以下查询
SELECT client.name AS Client,
category.name AS Category,
AVG(cart.subtotal) AS Total
FROM cart
INNER JOIN category ON category.id = cart.id_category
INNER JOIN clients ON clients.id = cart.id_client
GROUP BY cart.id_client,
cart.id_category
但我明白了:
+--------+----------+-------+
| Client | Category | Total |
+--------+----------+-------+
| Tom | Veggies | 1000 |
| Tom | Cheeses | 1500 |
| John | Cheeses | 2000 |
| Alice | Veggies | 1000 |
| Alice | Meat | 1000 |
| Alice | Cheeses | 1000 |
+--------+----------+-------+