列名称上的MySQL透视表日期
我一直在努力改造这张桌子:
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
不是我想要的,但也许更近了一步。我需要专家的帮助。我很感激你的建议。谢谢
解决方案
只能进行条件聚合:
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;
相关文章