产品价格的总和,按类别在MySQL中作为列

时间:2018-11-26 09:21:08

标签: mysql

我有3个表,customersproductscategories如下:

客户:

id      last_name
-----------------
100     Terry
200     molly
300     John

产品:

id  name        description     price   category_id     customer_id
-------------------------------------------------------------------
1   product1    lorem ipsum     150     10              100
2   product2    lorem ipsum     100     10              100
3   product3    lorem ipsum     300     20              200

类别:

id  name
---------
10  bags
20  toys
30  phones

所需结果:

customerID  customerLastName    bags    toys    phones
100         Terry               250     0       0
200         Molly               0       300     0
300         John                0       0       0

您所看到的理想结果是按类别分类的产品价格总和。因此对于第一个客户,他只拥有与类别bags相关的产品,因此我们应该有一个bags列,其中产品价格的总和为(product1为100,product2为150,总共是250个。

如果客户在某个类别中没有任何产品,则该类别列中的值应为0。

我已经尝试过了:

select 
customers.id as customerID, 
customers.last_name as customerLastName, 
SUM(CASE WHEN products.category_id = 10 THEN 1 ELSE NULL END) AS 'bags',
SUM(CASE WHEN products.category_id = 20 THEN 1 ELSE NULL END) AS 'toys',
SUM(CASE WHEN products.category_id = 30 THEN 1 ELSE NULL END) AS 'phones'
from customers
left join products on products.customer_id = customers.id
left join categories on products.category_id = categories.id
group by customers.id

但是我得到这个结果:

customerID  customerLastName    bags    toys    phones
100         Terry               2       0       0
200         Molly               0       1       0
300         John                0       0       0

1 个答案:

答案 0 :(得分:2)

THEN 1更改为THEN products.price,以汇总price的值。另外,如果您未指定ELSE NULL,则默认情况下仅为NULL

select 
  customers.id as customerID, 
  customers.last_name as customerLastName, 
  SUM(CASE WHEN products.category_id = 10 THEN products.price END) AS 'bags',
  SUM(CASE WHEN products.category_id = 20 THEN products.price END) AS 'toys',
  SUM(CASE WHEN products.category_id = 30 THEN products.price END) AS 'phones'
from customers
left join products on products.customer_id = customers.id
left join categories on products.category_id = categories.id
group by customers.id