[英]SQL: How do I change my query to get the following result?
For each customer-product pair, I need to calculate average sale of that product in each state.对于每个客户-产品对,我需要计算每个州该产品的平均销售额。
Actual table ("sales" table):实际表(“销售额”表):
cust | prod | state | quant
Bloom | Bread | NY | 1
Bloom | Butter| NJ | 2
.
.
.
My query:我的查询:
SELECT cust, prod, state, AVG(quant)
from sales
group by cust, prod, state;
Result:结果:
cust | prod | state | avg(quant)
Bloom | Bread | NY | 1
Bloom | Butter| NJ | 2
The result I want:我想要的结果:
cust | prod | NY | NJ
Bloom | Bread | 1 | 2
This is a pivot.这是一个支点。
SELECT
cust,
prod,
AVG(CASE WHEN state = 'NY' THEN quant END) AS 'NY',
AVG(CASE WHEN state = 'NJ' THEN quant END) AS 'NJ'
FROM sales
GROUP BY cust, prod
If you can't hard-code the states like that, see MySQL pivot row into dynamic number of columns for how to implement a dynamic pivot in a stored procedure.如果您不能像这样对状态进行硬编码,请参阅MySQL 将行转换为动态列数以了解如何在存储过程中实现动态数据透视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.