行列转化的问题,高手请解决
delcare @s varchar(8000)
set @s= 'select 日期 '
select @s=@s+ ',[ '+城市+ ']=max(case 城市 when ' ' '+城市+ ' ' ' then 温度 else 0 end) '
from (select distinct 城市 from 城市对应表) as a
set @s=@s+ ' from 表 group by 日期 '
exec(@s)
如果:我要转化的是一个动态sql查询后的结果 应该如何做呢?采用全局临时表能够做,但是考虑到全局临时表 多人使用时候可能会“冲突”,所以请求帮助!
------解决方案--------------------declare @sql nvarchar(4000)
set @sql = 'select 员工编号 '
select @sql = @sql + ',sum (case convert(nvarchar(1),[月]) when ' ' '+ convert(nvarchar(1),月) + ' ' ' then 奖金 else 0 end ) as [ ' + convert(nvarchar(1),月) + '月] '
from jj group by 月
select @sql = @sql + 'from (select * from jj )b group by 员工编号 '
exec(@sql)
--- 'from (select * from jj )b
这是动态查出来的.
------解决方案----------------------創建測試環境
create table holiday_type
(holiday_type Varchar(10),
holiday_type_name Nvarchar(20),
work_hour Numeric(10, 2))
Insert holiday_type Select 'A ', N '婚假 ', 8.00
Union All Select 'B ', N '产假 ', 8.00
Union All Select 'C ', N '丧假 ', 8.00
Union All Select 'D ', N '病假 ', 8.00
Union All Select 'E ', N 'tst ', 5.00
create table holiday_employees
(holiday_emp_seq Int,
emp_id Char(2),
start_day DateTime,
end_day DateTime,
holiday_type Varchar(10))
Insert holiday_employees Select 1, '01 ', '2007-08-01 00:00:00.000 ', '2007-08-02 00:00:00.000 ', 'A '
Union All Select 2, '01 ', '2007-08-07 00:00:00.000 ', '2007-08-09 00:00:00.000 ', 'B '
Union All Select 3, '01 ', '2007-08-12 00:00:00.000 ', '2007-08-20 00:00:00.000 ', 'C '
Union All Select 4, '02 ', '2007-08-12 00:00:00.000 ', '2007-08-20 00:00:00.000 ', 'C '
Union All Select 5, '03 ', '2007-08-12 00:00:00.000 ', '2007-08-20 00:00:00.000 ', 'C '
Union All Select 6, '03 ', '2007-08-01 00:00:00.000 ', '2007-08-03 00:00:00.000 ', 'A '
GO
--測試
Declare @S Varchar(8000)
Select @S = ' Select A.emp_id '
Select @S = @S + ', SUM(Case A.holiday_type When ' ' ' + holiday_type + ' ' ' Then B.work_hour * datediff(day, start_day, end_day) Else 0.0 End) As [ ' + holiday_type + '] '
F