可以说我有三个不同的MySQL表:
表产品:
id | name
1 Product A
2 Product B
表合作伙伴:
id | name
1 Partner A
2 Partner B
表销售额:
partners_id | products_id
1 2
2 5
1 5
1 3
1 4
1 5
2 2
2 4
2 3
1 1
我想得到一个表格,其中包含行和产品中的合作伙伴作为列.到目前为止,我能够得到这样的输出:
name | name | COUNT( * )
Partner A Product A 1
Partner A Product B 1
Partner A Product C 1
Partner A Product D 1
Partner A Product E 2
Partner B Product B 1
Partner B Product C 1
Partner B Product D 1
Partner B Product E 1
使用此查询:
SELECT partners.name, products.name, COUNT( * )
FROM sales
JOIN products ON sales.products_id = products.id
JOIN partners ON sales.partners_id = partners.id
GROUP BY sales.partners_id, sales.products_id
LIMIT 0 , 30
但我希望有类似的东西:
partner_name | Product A | Product B | Product C | Product D | Product E
Partner A 1 1 1 1 2
Partner B 0 1 1 1 1
问题是,我不知道我将拥有多少产品,因此列号需要根据products表中的行动态更改.
这个非常好的答案似乎不适用于mysql:T-SQL Pivot? Possibility of creating table columns from row values
解决方法:
不幸的是,MySQL没有PIVOT功能,这基本上就是你要做的.因此,您需要使用带有CASE语句的聚合函数:
select pt.partner_name,
count(case when pd.product_name = 'Product A' THEN 1 END) ProductA,
count(case when pd.product_name = 'Product B' THEN 1 END) ProductB,
count(case when pd.product_name = 'Product C' THEN 1 END) ProductC,
count(case when pd.product_name = 'Product D' THEN 1 END) ProductD,
count(case when pd.product_name = 'Product E' THEN 1 END) ProductE
from partners pt
left join sales s
on pt.part_id = s.partner_id
left join products pd
on s.product_id = pd.prod_id
group by pt.partner_name
由于您不了解产品,因此您可能希望动态执行此操作.这可以使用预先准备的语句来完成.
Dynamic pivot tables (transform rows to columns)
您的代码如下所示:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'count(case when Product_Name = ''',
Product_Name,
''' then 1 end) AS ',
replace(Product_Name, ' ', '')
)
) INTO @sql
from products;
SET @sql = CONCAT('SELECT pt.partner_name, ', @sql, ' from partners pt
left join sales s
on pt.part_id = s.partner_id
left join products pd
on s.product_id = pd.prod_id
group by pt.partner_name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
值得注意的是,GROUP_CONCAT默认限制为1024字节.您可以通过在程序持续时间内将其设置得更高来解决此问题,即. SET @@ group_concat_max_len = 32000;