MYSQL创建动态数据透视表

时间:2014-06-29 05:21:24

标签: mysql sql pivot pivot-table

这是我的查询

SELECT w.purchase_date, c.center_name, sum(w.final_kg) FROM wd_leaf_purchase w
join wd_leaves_supplier s on w.supplier_id = s.supplier_id
join wd_collection_center c on s.center_id = c.center_id
WHERE EXTRACT(MONTH FROM w.purchase_date) = MONTH(NOW())
AND EXTRACT(YEAR FROM w.purchase_date) = YEAR(NOW())
group by w.purchase_date, c.center_name;

以上查询的输出为

'2014-06-11', 'Main Center', '10.00'
'2014-06-20', 'Main Center', '10.00'
'2014-06-26', 'Main Center', '9.00'
'2014-06-26', 'Center B', '9.50'
'2014-06-27', 'Main Center', '73.00'
'2014-06-27', 'Center B', '73.00'
'2014-06-28', 'Main Center', '103.00'
'2014-06-28', 'Center B', '8.00'

但我需要输出如下。

'2014-06-11', 'Main Center', '10.00', 'Center B', '0'
'2014-06-20', 'Main Center', '10.00', 'Center B', '0'
'2014-06-26', 'Main Center', '9.00' 'Center B', '9.50'
'2014-06-27', 'Main Center', '73.00' 'Center B', '73.00'
'2014-06-28', 'Main Center', '103.00' 'Center B', '8.00'

如何编写查询以获得上述输出?

这是sqlfiddle

1 个答案:

答案 0 :(得分:1)

使用预准备语句动态构建列:

set @sql:=null;
select group_concat(distinct concat('sum(if(c.center_name="',center_name,'",w.final_kg,0)) `', center_name,'`') order by center_id)
from wd_collection_center
into @sql;

set @sql:=concat('SELECT w.purchase_date,', @sql, '
                  FROM wd_leaf_purchase w
                  join wd_leaves_supplier s on w.supplier_id = s.supplier_id
                  join wd_collection_center c on s.center_id = c.center_id
                  WHERE EXTRACT(MONTH FROM w.purchase_date) = MONTH(NOW())
                  AND EXTRACT(YEAR FROM w.purchase_date) = YEAR(NOW())
                  group by w.purchase_date;');

prepare st from @sql;
execute st;
deallocate prepare st;

fiddle