mysql数据透视查询中的总计

时间:2013-04-26 11:17:26

标签: mysql pivot

我有这个数据透视查询:

SELECT `fonte`, 

MAX(IF(month= '1', sell, NULL)) AS Gen,  
MAX(IF(month= '2', sell, NULL)) AS Feb, 
MAX(IF(month= '3', sell, NULL)) AS Mar, 
MAX(IF(month= '4', sell, NULL)) AS Apr, 
MAX(IF(month= '5', sell, NULL)) AS Mag, 
MAX(IF(month= '6', sell, NULL)) AS Giu, 
MAX(IF(month= '7', sell, NULL)) AS Lug, 
MAX(IF(month= '8', sell, NULL)) AS Ago, 
MAX(IF(month= '9', sell, NULL)) AS Sett, 
MAX(IF(month= '10', sell, NULL)) AS Ott, 
MAX(IF(month= '11', sell, NULL)) AS Nov, 
MAX(IF(month= '12', sell, NULL)) AS Dic,

FROM `pdl_dati` group by fonte

如何为月份''1'和月份='2'以及月份='3'和月份='4'以及月份='5'和月份='6'以及月份=插入“总计”? '7'和月='8'和月='9'和月='10'和月='11'和月='12'?

由于

1 个答案:

答案 0 :(得分:0)

如果您想要每月总计最后一行,可以使用GROUP BY WITH ROLLUP

SELECT `fonte`, 
  MAX(IF(month= '1', sell, NULL)) AS Gen,   -- do you want this to be sum?
  MAX(IF(month= '2', sell, NULL)) AS Feb, 
  MAX(IF(month= '3', sell, NULL)) AS Mar, 
  MAX(IF(month= '4', sell, NULL)) AS Apr, 
  MAX(IF(month= '5', sell, NULL)) AS Mag, 
  MAX(IF(month= '6', sell, NULL)) AS Giu, 
  MAX(IF(month= '7', sell, NULL)) AS Lug, 
  MAX(IF(month= '8', sell, NULL)) AS Ago, 
  MAX(IF(month= '9', sell, NULL)) AS Sett, 
  MAX(IF(month= '10', sell, NULL)) AS Ott, 
  MAX(IF(month= '11', sell, NULL)) AS Nov, 
  MAX(IF(month= '12', sell, NULL)) AS Dic
FROM `pdl_dati` 
group by fonte with ROLLUP;

作为旁注,如果您试图按月计算每个fonte的总数,我认为您可能希望使用sum而不是max。见Demo