2017-01-25 75 views
0

我有下表。我想添加2個新的列與選擇查詢,將顯示基於標誌類型的總和。根據現有列中的值創建2列

表:

tt  | company  | count | flag 
    -------------------------------------------- 
    123  | adeco  | 5  | 1 
    123  | mic   | 4  | 2 
    333  | manpower | 88  | 2 
    444  | linar  | 2  | 2 
    555  | dlank  | 3  | 1 

期望:

tt  | company  | total | flag | total_flag1 | total_flag2 
    ------------------------------------------------------------------- 
    123  | adeco  | 5  | 1  | 5   | 0 
    123  | mic   | 4  | 2  | 0   | 4 
    333  | manpower | 88  | 2  | 0   | 88 
    444  | linar  | 2  | 2  | 0   | 2 
    555  | dlank  | 3  | 1  | 3   | 0 

回答

2

通過您期望的結果,你應該對此,使用case whenif語法:

select 
    yourtable.*, 
    case when flag = 1 then `count` else 0 end as total_flag1, 
    case when flag = 2 then `count` else 0 end as total_flag2 
from yourtable 

或者

select 
    yourtable.*, 
    if(flag = 1, `count`, 0) as total_flag1, 
    if(flag = 2, `count`, 0) as total_flag2 
from yourtable 
0

我認爲你可以做你想做的使用相關子查詢或join

select t.*, tsum.total_flag1, tsum.total_flag2 
from t join 
    (select t.tt, 
      sum(case when flag = 1 then total else 0 end) as total_flag1, 
      sum(case when flag = 2 then total else 0 end) as total_flag2 
     from t 
     group by t.tt 
    ) tsum 
    on t.tt = tsum.tt; 
相關問題