MySQL将行数转换为dynamic数量的列

比方说,我有三个不同的MySQL表:

products

 id | name 1 Product A 2 Product B 

partners

 id | name 1 Partner A 2 Partner B 

sales

 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 

问题是,我不能告诉我有多less产品,所以列号需要dynamic改变,这取决于产品表中的行。

这个很好的答案似乎不适用于MySQL: T-SQL Pivot? 从行值创build表列的可能性

不幸的是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 

看演示与SQL小提琴

由于您不知道产品,您可能需要dynamic执行此操作。 这可以使用准备好的语句来完成。

dynamic数据透视表(将行转换为列)

你的代码看起来像这样:

 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; 

看演示与SQL小提琴

值得注意的是, GROUP_CONCAT默认限制在1024字节。 你可以通过在你的程序期间把它设置得更高来解决这个问题。 SET @@group_concat_max_len = 32000;