SQL 中行转成列的SQL语句

select sid,语文=isnull(sum(case course when '语文' then result end),0),
   数学=isnull(sum(case course when '数学' then result end),0),
   英语=isnull(sum(case course when '英语' then result end),0)
   from result 
   group by sid
   order by sid
   
   
   select project, SUM(m1) 一月,SUM(m1),SUM(m1) from (
      select project='差旅游费',case when mouth =1 then '一月' end 一月, money m1 from T1
      UNION all 
      select project='差旅游费',case when mouth =1 then '二月' end 二月 ,money m2 from T1
      union all 
      select project='差旅游费',case when mouth =1 then '三月' end 三月 ,money m3 from T1
            union all 
      select project='补助费用',case when mouth =1 then '一月' end 一月 ,money m1 from T1
      UNION all 
      select project='补助费用',case when mouth =1 then '二月' end 二月 ,money m2 from T1
      union all 
      select project='补助费用',case when mouth =1 then '三月' end 三月 ,money m3 from T1
   ) t0 
   group by t0.project
   
--   table_source
--PIVOT(
--聚合函数(value_column)
--FOR pivot_column
--IN(<column_list>)
--)
--- select*fromtb pivot(max(分数)for课程in(语文,数学,物理))a
select * from T1 pivor(sum(money)for project in (1,2,3,4,5)) a 

select project,
 sum(case mouth when 1 then money else 0 end) 一月,
 sum(case mouth when 2 then money else 0 end) 二月,
 sum(case mouth when 3 then money else 0 end) 三月,
  sum(case mouth when 4 then money else 0 end) 四月
from T1
group by project


SELECT project, [1] AS 一月, [2] AS 二月, [3] AS 三月, [4] AS 四月
FROM 
T1 PIVOT
(
SUM (money)
FOR mouth IN
( [1], [2], [3],[4] )
) AS pvt

ORDER BY project;

  

posted @ 2017-11-15 13:56  玄魄冰  阅读(207)  评论(0)    收藏  举报