mysql中的数据透视表类型输出

时间:2016-09-18 11:46:40

标签: mysql

我有这样的数据。

date           br   num   type
01092016       602   15    sb
01092016       602   10    mc
02092016       603   20    sb 
02092016       604   12     mc
03092016       605   11    sb 
03092016       605   13    mc

我希望以下列格式输出。

date             br                                      tot
                 602     603      604     605
             sb   mc   sb   mc   sb  mc   sb mc          sb    mc
01092016      15   10   0     0    0   0   0   0          15     10
02092016       0    0   20    0    0   12  0   0          20     12
03092016       0     0   0    0    0   0   11  13         11     13    

1 个答案:

答案 0 :(得分:0)

数据透视表类型输出可以在Mysql中实现,如此

select   tdate,
            sum(case when br = 602 and type = 'sb' then num else 0 end) as sb602,
            sum(case when br = 602 and type = 'mc' then num else 0 end) as mc602,
            sum(case when br = 603 and type = 'sb' then num else 0 end) as sb603,
            sum(case when br = 603 and type = 'mc' then num else 0 end) as mc603,
            sum(case when br = 604 and type = 'sb' then num else 0 end) as sb604,
            sum(case when br = 604 and type = 'mc' then num else 0 end) as mc604,
            sum(case when br = 605 and type = 'sb' then num else 0 end) as sb605,
            sum(case when br = 606 and type = 'mc' then num else 0 end) as mc606,

            sum(case when type = 'sb' then num else 0 end) as sbtot,
            sum(case when type = 'mc' then num else 0 end) as mctot         
from t
group by tdate

但是mysql的设计并不适合打印 - 您应该将其转换为报告工具 - 如果您拥有的分支和类型数量超过示例数量,那么将整个报告转移到报告工具可能会更好。< / p>