將sql橫向數據轉為列向

来源:互联网 发布:2015nba总决赛库里数据 编辑:程序博客网 时间:2024/04/26 06:07

對于表aa有如下字段:

月份,品號,品名,實際用量,標准用量

用select顯示為一年12月份的實際用量與標准用量:顯示如下

 年份 月份 品號 品名 實際用量 標准用量 2005 1 11 test 11 11 2005 2 11 test 11 11

現要求將顯示出每個月中的標准用量,與實際用量,并進行相應的對比

如:品號,品名,實際用量_1月,實際用量_2月...這個列格式

 品號 品名 實際用量_1月  實際用量_2月  標准用量_1月 標准用量_2月 11test 11 test 11 11 11test 11 test 11 11


select  品號,品名,

實際用量_1=case when 月份=1 then 實際用量 end, 
實際金額_1=case when 月份=1 then 實際金額 end,  

實際用量_2=case when 月份=2 then 實際用量 end, 
實際金額_2=case when 月份=2 then 實際金額 end, 
 
實際用量_3=case when 月份=3 then 實際用量 end, 
實際金額_3=case when 月份=3 then 實際金額 end, 
 
實際用量_4=case when 月份=4 then 實際用量 end, 
實際金額_4=case when 月份=4 then 實際金額 end, 
 
實際用量_5=case when 月份=5 then 實際用量 end, 
實際金額_5=case when 月份=5 then 實際金額 end, 
 
實際用量_6=case when 月份=6 then 實際用量 end, 
實際金額_6=case when 月份=6 then 實際金額 end, 
 
實際用量_7=case when 月份=7 then 實際用量 end, 
實際金額_7=case when 月份=7 then 實際金額 end, 
 
實際用量_8=case when 月份=8 then 實際用量 end, 
實際金額_9=case when 月份=9 then 實際金額 end, 
 
實際用量_10=case when 月份=10 then 實際用量 end, 
實際金額_10=case when 月份=10 then 實際金額 end, 
 
實際用量_11=case when 月份=11 then 實際用量 end, 
實際金額_11=case when 月份=11 then 實際金額 end, 
 
實際用量_12=case when 月份=12 then 實際用量 end, 
實際金額_12=case when 月份=12  then 實際金額 end 
from aa