[交流]行列转换
作 者: txlicenhe (马可)
http://expert.csdn.net/Expert/topic/2440/2440306.xml?temp=.175213
作 者: txlicenhe (马可)
http://expert.csdn.net/Expert/topic/2440/2440306.xml?temp=.175213
解决方案 »
- 文档浏览并发导致浏览量不准确
- 请大家帮我看看这个关系图是否有问题
- 如何将数据库中的表、存储过程等,生成一个SQL安装脚本,用户用这个脚本来安装程序???
- 请教: 如何留住我的临时表!!!
- 关于sqlserver2000中没有id列的分页问题
- 求一个SQL Server2000添加数据时的触发器
- 局域网中的SQL Server 2000的安装?
- SQL查询问题,高手帮忙!
- 触发时怎么样判断是插入,更新,删除.因为我要根据不同的动作做不同的语句.
- image字段类型,当图片大于32k时,出问题。
- 两个查询结果的连接问题
- 为什么我在Windows 2003 中装 SQL Server 2000企业版 的时候提示:不能安装??????
,field3=max(case field2 when 1 then 1 end)
,field4=max(case field2 when 2 then 2 end)
,field5=max(case field2 when 3 then 3 end)
,field6=max(case field2 when 4 then 4 end)
from 表
select field1=field1
,field3=max(case field2 when 1 then 1 end)
,field4=max(case field2 when 2 then 2 end)
,field5=max(case field2 when 3 then 3 end)
,field6=max(case field2 when 4 then 4 end)
from 表
group by field1
更多的参考我的贴子:化解字符串不能超过8000的方法
http://expert.csdn.net/Expert/topic/2303/2303308.xml?temp=.8503076
eg1:
Create table test (name char(10),km char(10),cj int)
go
insert test values('张三','语文',80)
insert test values('张三','数学',86)
insert test values('张三','英语',75)
insert test values('李四','语文',78)
insert test values('李四','数学',85)
insert test values('李四','英语',78)想变成姓名 语文 数学 英语
张三 80 86 75
李四 78 85 78
declare @sql varchar(8000)
set @sql = 'select name'
select @sql = @sql + ',sum(case km when '''+km+''' then cj end) ['+km+']'
from (select distinct km from test) as a
select @sql = @sql+' from test group by name'
exec(@sql)drop table test eg2:
有表A,
id pid
1 1
1 2
1 3
2 1
2 2
3 1
如何化成表B:
id pid
1 1,2,3
2 1,2
3 1
或者是从表B变成A(不要用游标)
以前有相似的列子,现在找不到了,帮帮忙!
--1.创建一个合并的函数
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+','+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go--调用自定义函数得到结果
select distinct id,dbo.fmerg(id) from 表A
2:
/*********** 行转列 *****************/
测试:
create table t1 (a int,b int,c int,d int,e int,f int,g int,h int)
insert t1 values(15, 9, 1, 0, 1, 2, 2, 0)declare @ varchar(8000)
set @=''
select @=@+rtrim(name)+' from t1 union all select ' from syscolumns where id=object_id('t1')
set @=left(@,len(@)-len(' from t1 union all select '))
--print @
exec('select '+@+' from t1')a
-----------
15
9
1
0
1
2
2
0