日期:2014-05-19  浏览次数:20510 次

行列转换问题,急,谢谢
表1
部门名     年周           发注数     比率
001           20                 1               10%
001           30                 4               10%
001           40                 5               10%
002           20                 1               20%
002           40                 1               20%
转化成表B
部门名       区分         20       30       40     统计

001             发注数     1           4         5       10
                  比率         10%       10%     10%   10%

002             发注数     1           0         1         2
                  比率         20%       -     20%     20%
谢谢,拜托了



------解决方案--------------------
create table 表1(部门名 varchar(10),年周 varchar(10),发注数 int,比率 varchar(10))
insert 表1
select '001 ', '20 ',1, '10% '
union select '001 ', '30 ',4, '10% '
union select '001 ', '40 ',5, '10% '
union select '002 ', '20 ',1, '20% '
union select '002 ', '40 ',1, '20% '


declare @sql varchar(8000),@sql1 varchar(8000)
select @sql= 'select * from (select 部门名, ' '发注数 ' ' as 区分 ',@sql1= ',cast(sum(发注数) as varchar) as 统计 from 表1 group by 部门名 union all select 部门名, ' '比率 ' ' as 区分 '
select @sql=@sql
+ ',cast(sum(case 年周 when '+cast(年周 as varchar)+ ' then 发注数 else 0 end) as varchar) as [ '+cast(年周 as varchar)
+ '] ',@sql1=@sql1+ ',isnull(max(case 年周 when '+cast(年周 as varchar)+ ' then 比率 end), ' '- ' ') as [ '+cast(年周 as varchar)+ '] '
from 表1 group by 年周

exec(@sql+@sql1+ ',max(比率) as 统计 from 表1 group by 部门名 ) t order by 部门名 ')
------解决方案--------------------
select * into #t from
(
select 部門名, '發註數 'as '區分 ', sum(case when 年周=20 then 發註數 else 0 end)as '二十 ',
sum(case when 年周=30 then 發註數 else 0 end)as '三十 ',
sum(case when 年周=40 then 發註數 else 0 end)as '四十 ',
sum(發註數)as 統計
from t
group by 部門名
union
select 部門名, '比率 'as '區分 ',max(case when 年周=20 then 比率 else '- ' end)as 比率1,
max(case when 年周=30 then 比率 else '- ' end)as 比率2,
max(case when 年周=40 then 比率 else '- ' end)as 比率3,