可以说我有三个不同的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
问题是我无法确定我将拥有多少个产品,因此列号需要根据产品表中的行动态更改。
这个很好的答案似乎不适用于mysql:T-SQL Pivot吗?根据行值创建表格列的可能性