gpt4 book ai didi

MySQL计算特定值的列

转载 作者:IT老高 更新时间:2023-10-28 12:59:15 25 4
gpt4 key购买 nike

我有以下 db 表,我希望能够统计每个销售人员的某些产品的销售实例。

|------------|------------|------------|
|id |user_id |product_id |
|------------|------------|------------|
|1 |1 |2 |
|2 |1 |4 |
|3 |1 |2 |
|4 |2 |1 |
|------------|------------|------------|

我希望能够创建如下结果集;

|------------|-------------|------------|------------|------------|
|user_id |prod_1_count |prod_2_count|prod_3_count|prod_4_count|
|------------|-------------|------------|------------|------------|
|1 |0 |2 |0 |1 |
|2 |1 |0 |0 |0 |
|------------|-------------|------------|------------|------------|

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

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;

我明白为什么这不起作用,因为对于每个带括号的 SELECT,user_id 与主 SELECT 语句中的外部 user_id 不匹配。

最佳答案

您可以使用 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

关于MySQL计算特定值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15815011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com