MySQL Pivot表日期在列名称上

时间:2016-09-15 11:01:30

标签: mysql sql pivot-table sqlcode

我一直试图改变这张桌子:

 Date         Table       Size in MB
------------  ----------- -----------
2016-09-14    table1      1.02
2016-09-15    table1      6.03        
2016-09-14    table2      120.0       
2016-09-15    table2      150.0       
2016-09-14    table3      50.0        
2016-09-15    table3      52.0        

进入这个:

Table        2016-09-14   2016-09-15   DIFF
-----------  -----------  -----------  -------
table1       1.02         6.03          5.01
table2       120.0        150.0         30.0
table3       50.0         52.0          2.0

透视表形成原始表格,但将日期字段放入mb列中的大小的列名称中,如果可能,请在最后一列上区分它们。

到目前为止,我可以做到这一点

Table       Date1        Date2       
----------- -----------  ----------- 
table1      2016-09-14   2016-09-15
table2      2016-09-14   2016-09-15
table3      2016-09-14   2016-09-15

使用上一篇关于数据透视表的代码

select `Table`,
  max(case when rownum = 1 then date end) Date1,
  max(case when rownum = 2 then date end) Date2
from
(
  select table_name AS `Table`,
    date,round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`,
    @row:=if(@prev=table_name, @row,0) + 1 as rownum,
    @prev:=table_name 
  FROM DBA_DB.table_growth_history, (SELECT @row:=0, @prev:=null) r
  order by table_name, date
) s
group by table_name
order by table_name, date

不是我想要的,但可能更接近一步。我需要专家的帮助。我很感激任何建议。感谢

1 个答案:

答案 0 :(得分:0)

您可以只进行条件聚合:

select table_name,
       max(case when date = '2016-09-14' then round(((data_length + index_length) / 1024 / 1024), 2) end) as size_20160915,
       max(case when date = '2016-09-15' then round(((data_length + index_length) / 1024 / 1024), 2) end) as size_20160916,
       (max(case when date = '2016-09-15' then round(((data_length + index_length) / 1024 / 1024), 2) end) -
        max(case when date = '2016-09-14' then round(((data_length + index_length) / 1024 / 1024), 2) end)
       ) as diff
from DBA_DB.table_growth_history t
where date in ('2016-09-14', '2016-09-15')
group by table_name;