sql语句如何实现将已经搜索到的Recordset,横向插入到令一个临时的表里.
sql语句如何实现将已经搜索到的Recordset,横向插入到令一个临时的表里.然后建一个job每隔两个小时导出成csv文件,文件名为yyyymmddhh.csv. 如:2007041421.csv
select * from table1得到的记录集为.
Name Course Grade
刘三 maths 45
刘三 Chinese 39
刘三 English 56
王五 maths 77
王五 Chinese 89
王五 English 48
插入到另一张临时表后为:
Name Maths Chinese English
刘三 45 39 56
王五 77 89 48
整个如何用语句来实现,关键是临时表的字段如何生成等等.
接着又如何用job来导出呢?
非常紧急,如能解决,可以另外加分----
------解决方案--------------------行列转换的代码:
declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',sum(case course when ' ' '+course+ ' ' ' then grade else 0 end) as ' ' '+course+ ' ' ' ' from (select distinct course from table1) t
set @sql= 'select name '+@sql+ ' from table1 group by name '
exec(@sql)
------解决方案--------------------drop table table1
go
create table table1(name varchar(10),course varchar(10),grade int)
insert into table1
select '刘三 ', 'maths ',45
union select '刘三 ', 'Chinese ',39
union select '刘三 ', 'English ',56
union select '王五 ', 'maths ',77
union select '王五 ', 'Chinese ',89
union select '王五 ', 'English ',48
declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',sum(case when course= ' ' '+course+ ' ' ' then grade else 0 end) as ' ' '+course+ ' ' ' '
from (select distinct course from table1)t
exec( 'select name '+@sql+ ' from table1 group by name ')
/*
name Chinese English maths
---------- ----------- ----------- -----------
刘三 39 56 45
王五 89 48 77
*/
------解决方案--------------------declare @sql varchar(4000)
set @sql= ' '
select @sql=@sql+ ', '+quotename(course)+ '=max(case course when '
+quotename(course, ' ' ' ')+ ' then grade else 0 end) '
from table1
group by name
set @sql= 'select Name '+@sql+ 'into #
from table1 group by name '
print @sql--显示语句
复制执行就行了
------解决方案--------------------Declare @cols nvarchar(max);
WITH CTECourse(Course)
As
(
Select Distinct Course From table1
)
Select @cols = IsNull(@cols + ',[ ', '[ ') + Course + '] ' From CTECourse
DECLARE @sql AS nvarchar(MAX)
SET @sql = N 'SELECT *
FROM (SELECT [Name], [Course], [Grade]