2016-09-21 220 views
0

我想用下面的公式來創建一個子表的新表:有沒有辦法在MYSQL中使用max()函數創建多個列?

create table if not exists `new_table` as 
    select * from (
     select descrip, 
     max(case when ID = 1.01 then value else 0 end) 1.01 
     from(
      select ID, `JUL-08` value, 1 descrip 
      from original_table 
      union all 
      select ID, `AGO-08` value, 2 descrip 
      from original_table 
      union all 
      select ID, `SET-08` value, 3 descrip 
      from original_table 
      union all 
      select ID, `OUT-08` value, 4 descrip 
      from original_table 
      union all 
      select ID, `NOV-08` value, 5 descrip 
      from original_table 
      union all 
      select ID, `DEZ-08` value, 6 descrip 
      from original_table 
     ) src 
     group by descrip 
    ) as `new_table`; 

公式效果很好,它創建它的目的是創建表,但我不知道是否max函數可能用於爲同一個表創建多個列,或者如果我必須重複每個ID的整個公式,則需要創建一個新表或者在同一個公式中重複max()函數。

+0

'select'列表中的單個表達式(如max(...))只能創建一個列。期。無論你需要重複所有idst的表達式,還是需要創建一個程序來爲你生成sql語句。你想要的最有可能是一個動態的關鍵點 – Shadow

+0

你也許可以用group by語句做到這一點,但我會要求查看來自original_table的示例數據 – kbball

+0

這將是這樣的:create table'original_table'('ID' float不是null,'jul-08' int,'aug-08' int,'sep-08' int,'oct-08' int, \t'nov-08' int,'dec-08' int,'jan- 09' int,'feb-09' int,'mar-09' int,'apr-09' int, 'may-09' int,'jun-09' int) INSERT INTO'origiral_table' ,08年,08年,08年,08年,08年,08年,08年,08年,08年,1月,09年1月,1月,\t'mar-09','apr-09','may-09','jun-09') VALUES(1.01,8,8,0,0,0,0,0,0,0,0, 0,0), \t(1.02,10,10,0,0,0,0,6,7 ,10,5,2,0) (2.01,0,0,3,6,11,3,1,0,0,0,0,1), (3.01,1,0,1,5, 27,13,11,12,9,6,1,0); – jlsalles

回答

0

您可以隨意重複表達式。你需要給他們不同的名字。

我也注意到你有太多的子查詢表達式:

create table if not exists `new_table` as 
    select descrip, 
      max(case when ID = 1.01 then value else 0 end) as `1.01`, 
      max(case when ID = 2.01 then value else 0 end) as `2.01` 
    from (select ID, `JUL-08` as value, 1 as descrip 
      from original_table 
      union all 
      select ID, `AGO-08` as value, 2 as descrip 
      from original_table 
      union all 
      select ID, `SET-08` as value, 3 as descrip 
      from original_table 
      union all 
      select ID, `OUT-08` as value, 4 as descrip 
      from original_table 
      union all 
      select ID, `NOV-08` as value, 5 as descrip 
      from original_table 
      union all 
      select ID, `DEZ-08` as value, 6 as descrip 
      from original_table 
     ) src 
    group by descrip; 

我不建議您命名的列數(或SQL關鍵字爲此事)。但是,如果你這樣做,你應該使用轉義字符清楚你正在做什麼。我會推薦一些更像id_1_01的東西,所以列名不需要轉義。

相關問題