[英]MySQL Pivot table dates on column name
I've been hitting my heat trying to transform this table: 我一直在努力改变这张桌子:
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
Into this: 变成这个:
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
A pivot table form the original table but putting the date field into the column name for the size in mb column and if possible do the difference between them on a last column. 数据透视表构成原始表,但将日期字段放入mb列大小的列名称中,如果可能,请在最后一列之间进行区别。
So far I could do this 到目前为止,我可以做到这一点
Table Date1 Date2
----------- ----------- -----------
table1 2016-09-14 2016-09-15
table2 2016-09-14 2016-09-15
table3 2016-09-14 2016-09-15
using the code from a previous post about pivot tables 使用上一篇有关数据透视表的文章中的代码
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
Not what I want but maybe a step closer. 不是我想要的,但也许离我更近了。 I need help from the experts.
我需要专家的帮助。 I appreciate any advice.
我感谢任何建议。 Thanks
谢谢
You can just do conditional aggregation: 您可以执行条件聚合:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.