我已将查询编写为
SELECT c.customer_name, o.net_total,
GROUP_CONCAT(
'SUM(IF(ps.product_sku_name = ''',
product_sku_name,
''', o.net_total,0)) AS ',
product_sku_name
)
FROM products_sku ps
LEFT JOIN products AS p
ON p.product_id = ps.product_id
left join order_lines ol on ol.product_sku_id = ps.product_sku_id
left join orders o on o.order_id = ol.order_id
left join customers c on c.customer_id = o.customer_id
GROUP BY ps.product_sku_id
得到结果
customer_name net_total GROUP_CONCAT( 'SUM(IF(ps.product_sku_name = ''', product_sku_name, ''', o.net_total,0)) AS ', product_sku_name )
Customer2 126.0000 SUM(IF(ps.product_sku_name = 'PSKU Name 1', o.net_total,0)) AS PSKU Name 1,SUM(IF(ps.product_sku_name = 'PSKU Name 1', o.net_total,0)) AS PSKU Name 1,SUM(IF(ps.product_sku_name = 'PSKU Name 1', o.net_total,0)) AS PSKU Name 1
Customer1 105.0000 SUM(IF(ps.product_sku_name = 'PSKU Name2', o.net_total,0)) AS PSKU Name2
NULL NULL SUM(IF(ps.product_sku_name = 'PSKU Name3', o.net_total,0)) AS PSKU Name3
NULL NULL SUM(IF(ps.product_sku_name = 'Product SKU 4', o.net_total,0)) AS Product SKU 4
Customer1 945.0000 SUM(IF(ps.product_sku_name = 'PSKU Name4', o.net_total,0)) AS PSKU Name4
Customer1 2159.3600 SUM(IF(ps.product_sku_name = 'Jordon', o.net_total,0)) AS Jordon,SUM(IF(ps.product_sku_name = 'Jordon', o.net_total,0)) AS Jordon
我希望结果为
customer_name PSKU Name 1 PSKU Name 2 PSKU Name 3 PSKU Name 4 Jordon
Customer2 126 NULL NULL NULL NULL
Customer1 NULL 105 NULL 945 2159
我已提及version 2网站进行此查询
请回复...提前致谢
答案 0 :(得分:1)
您的尝试在构建查询方面有所帮助。但是你需要一个存储过程来构建和来执行它。
有关此类代码,请参阅http://mysql.rjweb.org/doc.php/pivot。