簡體   English   中英

MySQL Pivot表日期在列名上

[英]MySQL Pivot table dates on column name

我一直在努力改變這張桌子:

 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM