假设我有三个不同的 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?从行值创建表列的可能性