sqlserver 多行轉多列實例

查詢結果字段介紹:c_ex49是業務員id,tmonth是年-月,tamt是對應月的金額,想要最後查詢的效果是:把每個業務員的每個月的金額顯示成一行,我這裏只到了1-10月份,不過顯示還是要顯示1-12月的,沒有的就顯示0

上圖使用多行轉多列,效果爲:

 

下面是具體步驟:

 

然後,執行上面的邏輯後,就由最初的多行變成了多列

最初的:

select c_ex49,CONVERT(VarChar(7),c_starttime, 120) as tmonth,SUM(CAST(c_ex9 as float)) as tamt from CRM_CONTRACT 
       where CONVERT(VarChar(7),c_starttime, 120)>='2019-01' and CONVERT(VarChar(7),c_starttime, 120)<='2019-12' and c_ex49='scrmsass_yangli'
group by c_ex49,CONVERT(VarChar(7),c_starttime, 120)

 

執行後的:

select c_ex49,
    sum(oneMonth) as oneMonth,sum(twoMonth) as twoMonth,sum(threeMonth) as threeMonth,sum(fourMonth) as fourMonth,sum(fiveMonth) as fiveMonth,sum(sixMonth) as sixMonth,
    sum(sevenMonth) as sevenMonth,sum(eightMonth) as eightMonth,sum(nineMonth) as nineMonth,sum(tenMonth) as tenMonth,sum(elevenMonth) as elevenMonth,sum(telvMonth) as telvMonth from (
    select c_ex49,
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-01' then c_ex9 else '0.0' end as float)) 'oneMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-02' then c_ex9 else '0.0' end as float)) 'twoMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-03' then c_ex9 else '0.0' end as float)) 'threeMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-04' then c_ex9 else '0.0' end as float)) 'fourMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-05' then c_ex9 else '0.0' end as float)) 'fiveMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-06' then c_ex9 else '0.0' end as float)) 'sixMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-07' then c_ex9 else '0.0' end as float)) 'sevenMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-08' then c_ex9 else '0.0' end as float)) 'eightMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-09' then c_ex9 else '0.0' end as float)) 'nineMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-10' then c_ex9 else '0.0' end as float)) 'tenMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-11' then c_ex9 else '0.0' end as float)) 'elevenMonth',
    sum(CAST(case when CONVERT(VarChar(7),c_starttime, 120)='2019-12' then c_ex9 else '0.0' end as float)) 'telvMonth'
    from CRM_CONTRACT where CONVERT(VarChar(7),c_starttime, 120)>='2019-01' and CONVERT(VarChar(7),c_starttime, 120)<='2019-12' and c_ex49='scrmsass_yangli'
    group by c_ex49,CONVERT(VarChar(7),c_starttime, 120)  
) t1 group by c_ex49


 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章