--行列互转
/******************************************************************************************************************************************************
以学生成绩为例子,比较形象易懂整理人:中国风(Roy)日期:2008.06.06
******************************************************************************************************************************************************/--1、行互列
--> --> (Roy)生成測試數據
if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
--2000方法:
动态:declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+' from Class group by [Student]')
生成静态:select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end)
from
Class
group by [Student]GO
动态:declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')生成静态:
select *
from
Class
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b生成格式:
/*
Student 数学 物理 英语 语文
------- ----------- ----------- ----------- -----------
李四 77 85 65 65
张三 87 90 82 78(2 行受影响)
*/------------------------------------------------------------------------------------------
go
--加上总成绩(学科平均分)--2000方法:
动态:declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
from Class group by[Course]
exec('select [Student]'+@s+',[总成绩]=sum([Score]) from Class group by [Student]')--加多一列(学科平均分用avg([Score]))生成动态:select
[Student],
[数学]=max(case when [Course]='数学' then [Score] else 0 end),
[物理]=max(case when [Course]='物理' then [Score] else 0 end),
[英语]=max(case when [Course]='英语' then [Score] else 0 end),
[语文]=max(case when [Course]='语文' then [Score] else 0 end),
[总成绩]=sum([Score]) --加多一列(学科平均分用avg([Score]))
from
Class
group by [Student]go--2005方法:动态:declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号
exec('select [Student],'+@s+',[总成绩] from (select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a
pivot (max([Score]) for [Course] in('+@s+'))b ')生成静态:select
[Student],[数学],[物理],[英语],[语文],[总成绩]
from
(select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a --平均分时用avg([Score])
pivot
(max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b 生成格式:/*
Student 数学 物理 英语 语文 总成绩
------- ----------- ----------- ----------- ----------- -----------
李四 77 85 65 65 292
张三 87 90 82 78 337(2 行受影响)
*/go--2、列转行
--> --> (Roy)生成測試數據
if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int)
Insert Class
select N'李四',77,85,65,65 union all
select N'张三',87,90,82,78
Go--2000:动态:declare @s nvarchar(4000)
select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''')--isnull(@s+' union all ','') 去掉字符串@s中第一个union all
+',[Score]='+quotename(Name)+' from Class'
from syscolumns where ID=object_id('Class') and Name not in('Student')--排除不转换的列
order by Colid
exec('select * from ('+@s+')t order by [Student],[Course]')--增加一个排序生成静态:
select *
from (select [Student],[Course]='数学',[Score]=[数学] from Class union all
select [Student],[Course]='物理',[Score]=[物理] from Class union all
select [Student],[Course]='英语',[Score]=[英语] from Class union all
select [Student],[Course]='语文',[Score]=[语文] from Class)t
order by [Student],[Course]go
--2005:动态:declare @s nvarchar(4000)
select @s=isnull(@s+',','')+quotename(Name)
from syscolumns where ID=object_id('Class') and Name not in('Student')
order by Colid
exec('select Student,[Course],[Score] from Class unpivot ([Score] for [Course] in('+@s+'))b')go
select
Student,[Course],[Score]
from
Class
unpivot
([Score] for [Course] in([数学],[物理],[英语],[语文]))b生成格式:
/*
Student Course Score
------- ------- -----------
李四 数学 77
李四 物理 85
李四 英语 65
李四 语文 65
张三 数学 87
张三 物理 90
张三 英语 82
张三 语文 78(8 行受影响)
*/
解决方案 »
- 如果实现这样的SQL取数查询
- 一个小问题
- 求助:向各位大哥请教一个 output 参数的问题,谢谢!
- 请 vivianfdlpw() 来领分·真的谢谢你
- 字段超长问题
- 我的这点程序怎么运行有错?(内付原码)
- 我想在单机上模拟学习sqlserver2000,请问是否一定要在2000server下安装。2000professional可以吗?功能上有差别吗?
- 问英文字段名转换为中文标题显示的sql语句
- 一个送分的问题!
- SQL SERVER 2000中,字段注释内容是保存在哪个表中?---一定给分!(系统只让给56)
- sql server 2005 中workstation component 安装失败!
- 关于大型数据库 设计问题~
set @s='select 日期 as [日期\名称] '
select @s=select @s+',max(case 名称 when '''+名称+''' then 总数 else 0 end) ['+名称+']'
from (select distinct 名称 from 库存表) t
select @s=@s+' from 库存表 group by 日期'
exec(@s)动态SQL
set @s='select 日期 as [日期\名称] '
select @s=@s+',max(case 名称 when '''+名称+''' then 总数 else 0 end) ['+名称+']'
from (select distinct 名称 from 库存表) t
select @s=@s+' from 库存表 group by 日期'
exec(@s)多出了个select ,改一下.
CREATE TABLE Table1(col1 varchar(10),col2 varchar(10),col3 int)insert into Table1 values('2009-04-02','C',1)
insert into Table1 values('2009-04-05','B',10)
insert into Table1 values('2009-03-31','D',11)
insert into Table1 values('2009-04-07','D',5)
insert into Table1 values('2009-03-31','A',1000)
declare @sql varchar(8000)
set @sql =''
select @sql = @sql+','+col2+'=sum(case when col2='''+col2+''' then col3 else 0 end)' from (select distinct col2 from Table1) a
SET @sql ='select col1,'+right(@sql,len(@sql)-1)+' from Table1 group by col1'
exec(@sql)drop table Table1
/*
col1 A B C D
---------- ----------- ----------- ----------- -----------
2009-03-31 1000 0 0 11
2009-04-02 0 0 1 0
2009-04-05 0 10 0 0
2009-04-07 0 0 0 5(4 行受影响)*/
insert into tb values('张三' , '语文' , 74)
insert into tb values('张三' , '数学' , 83)
insert into tb values('张三' , '物理' , 93)
insert into tb values('李四' , '语文' , 74)
insert into tb values('李四' , '数学' , 84)
insert into tb values('李四' , '物理' , 94)
select UserName,sum(case when Subject= '数学' then Score else 0 end) [数学],sum(case when Subject= '物理' then Score else 0 end) [物理],sum(case when Subject= '语文' then Score else 0 end) [语文]
declare @sql varchar(1000)
set @sql='select UserName'
select @sql=@sql+',sum(case when Subject= ''' +Subject+ ''' then Score else 0 end) ['+Subject+']' from (select distinct Subject from tb)aset @sql = @sql + ' from tb group by UserName'
print @sql
exec(@sql)
--讲解:--这个是第一次执行
select 姓名,max(case 课程 when '数学' then 分数 else 0 end) [数学],
--这个是第二次
select 姓名,max(case 课程 when '数学' then 分数 else 0 end) [数学], max(case 课程 when '物理' then 分数 else 0 end) [物理] ,
--这个是第三次
select 姓名,max(case 课程 when '数学' then 分数 else 0 end) [数学], max(case 课程 when '物理' then 分数 else 0 end) [物理] , max(case 课程 when '语文' then 分数 else 0 end) [语文]
--这个的数量来自于
(select distinct 课程 from tb)--这里只有3们课程create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
gocreate function dbo.f_str(@id int) returns varchar(100)
as
begin
declare @str varchar(1000)
set @str = ''
select @str = @str + ',' + cast(value as varchar) from tb where id = @id
set @str = right(@str , len(@str) - 1)
return @str
end
go--调用函数
select id , value = dbo.f_str(id) from tb group by iddrop function dbo.f_str
drop table tb
我只说一个地方
select @str = @str + ',' + cast(value as varchar) from tb where id = @id
你把这个看懂就明白了
例如当@id=1
select @str = @str + ',' + cast(value as varchar) from tb where id = 1
把满足id=1的str值通过','累加
当id是动态的就是1或者2...是当满足1的查询完了,把值付给str之后
在查询满足2的直到所有的ID完为止
这样明白了吧
insert into tb values('2009-04-05','B',10)
insert into tb values('2009-03-31','D',11)
insert into tb values('2009-04-07','D',5)
insert into tb values('2009-03-31','A',1000)declare @s varchar(8000)
set @s='select 日期 as [日期\名称] '
select @s=@s+',max(case 名称 when '''+名称+''' then 总数 else 0 end) ['+名称+']'
from (select distinct 名称 from tb) t
select @s=@s+' from tb group by 日期'
exec(@s)drop table tb/*
日期\名称 A B C D
---------- ----------- ----------- ----------- -----------
2009-03-31 1000 0 0 11
2009-04-02 0 0 1 0
2009-04-05 0 10 0 0
2009-04-07 0 0 0 5(4 行受影响)
*/
--> 测试数据: [table1]
if object_id('[table1]') is not null drop table [table1]
create table [table1] (日期 datetime,名称 varchar(1),总数 int)
insert into [table1]
select '2009-04-02','C',1 union all
select '2009-04-05','B',10 union all
select '2009-03-31','D',11 union all
select '2009-04-07','D',5 union all
select '2009-03-31','A',1000
go
--创建存储过程
create proc p_wsp
@star datetime,
@end datetime
as
create table #(dt datetime)
while(@star<=@end)
begin
insert into # select @star
set @star=dateadd(dd,1,@star)
end
declare @sql varchar(8000)
set @sql='select dt[日期\名称]'
select @sql=@sql+',['+name+']=max(case 名称 when '''+name+''' then 总数 else 0 end)'
from (select name='A' union all select 'B' union all select 'C' union all select 'D' union all select 'E' union all select 'F')a
set @sql=@sql+' from # a left join table1 b on a.dt=b.日期 group by dt'
exec(@sql)
go--执行
exec p_wsp @star='2009-03-31',@end='2009-04-07'
----------------------- ----------- ----------- ----------- ----------- ----------- -----------
2009-03-31 00:00:00.000 1000 0 0 11 0 0
2009-04-01 00:00:00.000 0 0 0 0 0 0
2009-04-02 00:00:00.000 0 0 1 0 0 0
2009-04-03 00:00:00.000 0 0 0 0 0 0
2009-04-04 00:00:00.000 0 0 0 0 0 0
2009-04-05 00:00:00.000 0 10 0 0 0 0
2009-04-06 00:00:00.000 0 0 0 0 0 0
2009-04-07 00:00:00.000 0 0 0 5 0 0
goinsert ta select '2009-04-02' , 'C' , 1
insert ta select '2009-04-05' , 'B' , 10
insert ta select '2009-03-31' , 'D' , 11
insert ta select '2009-04-07' , 'D' , 5
insert ta select '2009-03-31' , 'A' , 1000
insert ta select '2009-04-01' , 'E' , 1
insert ta select '2009-04-02' , 'F' , 1
go
set nocount on
declare @begin datetime,@end datetime, @sql varchar(8000)
set @begin='2009-03-31'
set @end='2009-04-07'
set @sql='select [日期 \ 名称 ]=convert(varchar(10),日期,120)'select * into #temp from
(select 日期,名称,总数 from ta where convert(varchar(10),日期,120) between convert(varchar(10),@begin,120) and convert(varchar(10),@end,120)
union all
select dateadd(dd,b.number,@begin),a.名称,0 from (select distinct 名称 from ta) a,master..spt_values b where b.type='p' and b.number between 0 and datediff(dd,@begin,@end)) c select @sql=@sql+',['+名称+']=sum(case 名称 when '''+名称+''' then 总数 else 0 end) ' from (select distinct 名称 from ta) aset @sql=@sql+ 'from #temp group by 日期 order by 日期'
exec (@sql)
drop table ta,#temp/*
日期 \ 名称 A B C D E F
---------- ----------- ----------- ----------- ----------- ----------- -----------
2009-03-31 1000 0 0 11 0 0
2009-04-01 0 0 0 0 1 0
2009-04-02 0 0 1 0 0 1
2009-04-03 0 0 0 0 0 0
2009-04-04 0 0 0 0 0 0
2009-04-05 0 10 0 0 0 0
2009-04-06 0 0 0 0 0 0
2009-04-07 0 0 0 5 0 0*/
declare @beginDate datetime
declare @endDate datetimeset @beginDate = '2009-03-31'
set @endDate = '2009-04-07'
declare @i int
set @i = 0
while @i<=datediff(day,@beginDate,@endDate)
begin
insert into ccc(日期) values( convert(nvarchar(10),dateadd(day,@i,@beginDate),120))
set @i = @i +1
end
CREATE TABLE Table1(col1 varchar(10),col2 varchar(10),col3 int)insert into Table1 values('2009-04-02','C',1)
insert into Table1 values('2009-04-05','B',10)
insert into Table1 values('2009-03-31','D',11)
insert into Table1 values('2009-04-07','D',5)
insert into Table1 values('2009-03-31','A',1000)declare @sql varchar(8000)
set @sql =''
select @sql = @sql+','+col2+'=sum(case when col2='''+col2+''' then col3 else 0 end)' from (select distinct col2 from Table1) a
SET @sql ='select 日期,'+right(@sql,len(@sql)-1)+' from ccc c left join Table1 t on c.日期 = t.col1 group by 日期'
exec(@sql)
日期 A B C D
---------- ----------- ----------- ----------- -----------
2009-03-31 1000 0 0 11
2009-04-01 0 0 0 0
2009-04-02 0 0 1 0
2009-04-03 0 0 0 0
2009-04-04 0 0 0 0
2009-04-05 0 10 0 0
2009-04-06 0 0 0 0
2009-04-07 0 0 0 5(8 row(s) affected)