• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: | 推荐给好友 上一篇 | 下一篇

行列转换 交叉表

发布: 2007-7-02 11:08 | 作者: admin | 来源: | 查看: 14次 | 进入软件测试论坛讨论

领测软件测试网
总结了一些有代表性的贴子,具体见http://expert.csdn.net/Expert/topic/2440/2440306.xml?temp=.6941645

1: 列转为行:
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

 

文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备2023014753号-2
技术支持和业务联系:info@testage.com.cn 电话:010-51297073

软件测试 | 领测国际ISTQBISTQB官网TMMiTMMi认证国际软件测试工程师认证领测软件测试网