MySQL计算特定值的列

Chr*_*ron 38 mysql

我有以下数据库表,我希望能够计算每个销售人员的某些产品的销售实例.

|------------|------------|------------|
|id          |user_id     |product_id  |
|------------|------------|------------|
|1           |1           |2           |
|2           |1           |4           |
|3           |1           |2           |
|4           |2           |1           |
|------------|------------|------------|
Run Code Online (Sandbox Code Playgroud)

我想能够创建如下的结果集;

|------------|-------------|------------|------------|------------|
|user_id     |prod_1_count |prod_2_count|prod_3_count|prod_4_count|
|------------|-------------|------------|------------|------------|
|1           |0            |2           |0           |1           |
|2           |1            |0           |0           |0           |
|------------|-------------|------------|------------|------------|
Run Code Online (Sandbox Code Playgroud)

我正在使用这些数据创建图表,并且再次(如今天早些时候)我无法计算列总数.我试过了;

SELECT user_id, 
(SELECT count(product_id) FROM sales WHERE product_id = 1) AS prod_1_count,
(SELECT count(product_id) FROM sales WHERE product_id = 2) AS prod_2_count,
(SELECT count(product_id) FROM sales WHERE product_id = 3) AS prod_3_count,
(SELECT count(product_id) FROM sales WHERE product_id = 4) AS prod_4_count 
FROM sales GROUP BY user_id; 
Run Code Online (Sandbox Code Playgroud)

我可以看到为什么这不起作用,因为对于每个括号中的SELECT,user_id与主SELECT语句中的外部user_id不匹配.

有人可以帮帮我吗?

谢谢

Ike*_*ker 87

您可以使用SUM和执行此操作CASE:

select user_id,
  sum(case when product_id = 1 then 1 else 0 end) as prod_1_count,
  sum(case when product_id = 2 then 1 else 0 end) as prod_2_count,
  sum(case when product_id = 3 then 1 else 0 end) as prod_3_count,
  sum(case when product_id = 4 then 1 else 0 end) as prod_4_count
from your_table
group by user_id
Run Code Online (Sandbox Code Playgroud)

  • 你不能只做`sum(product_id = 1)`?`product_id = 1`是一个布尔表达式; 没有开关盒,它自然会返回1或0. (4认同)

Tar*_*ryn 20

您正试图转动数据.MySQL没有pivot函数,所以你必须使用带有CASE表达式的聚合函数:

select user_id,
  count(case when product_id = 1 then product_id end) as prod_1_count,
  count(case when product_id = 2 then product_id end) as prod_2_count,
  count(case when product_id = 3 then product_id end) as prod_3_count,
  count(case when product_id = 4 then product_id end) as prod_4_count
from sales
group by user_id;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

  • 我希望我可以给这1000个箭头.旋转只是点击. (2认同)