SQL SERVER一列多行转一行的方法详解
(2014-12-16 15:28:52)
标签:
sqlserver多行转一行sqlserver多行变一行sql一列多行变一行sqlserver字符拼接sql多行合并一行 |
分类: 数据库学习 |
一、创建测试表
drop table test
create table test(id int,val varchar(10))
--插入测试值
insert
select
union
select
union
select
union
select
union
select
union
select
union
select
union
select
union
select
union
select
-- 查询表数据
select
id
----------- ----------
1
1
1
2
3
3
4
4
4
4
--目标数据
id
----------- ----------
1
2
3
4
二、SQL SERVER2000及SQL
SERVER2005中实现方法示例
1、通过调用自定义函数实现
--创建函数
create
returns varchar(100)
as
begin
declare @str varchar(200)
set @str=''
select
select
return @str
end
--调用函数查询
select
from
group
go
drop function fun_test
运行结果:
id
----------- ------------------------------
1
2
3
4
2、通过游标来处理
declare
declare cur_test cursor for
select
declare @id_old int,@id int,@val varchar(20),@s varchar(100)
open cur_test
fetch cur_test into @id,@val
select
while
begin
if @id=@id_old
select
else
begin
insert
select
select
end
fetch cur_test into @id,@val
end
insert
select
close cur_test
deallocate cur_test
select * from @tab
运行结果:
id
----------- ------------------------------
1
2
3
4
3、通过临时表实现字符串合并处理
declare
declare
insert
select
from
order
update
set
--select * from @tab
select
运行结果:
id
----------- -------------------- -----------
1
2
3
4
4、通过拼接字符串处理
--每组小于等于2条记录时字符合并处理
select
from
group
运行结果:
id
----------- ---------------------
1
2
3
4
--每组小于等于3条记录时字符合并处理
select
+case when count(*)>=3 then ','+(select top 1 val from test
where id=a.id and val not in (min(a.val),max(a.val))) else ''
end
+case when count(*)>=2 then ','+max(val) else '' end as
val
from
group
运行结果:
id
----------- --------------------------------
1
2
3
4
--每组小于等于4条记录时字符合并处理
select
+case when count(*)=4 then ','+(select top 1 val from test where
id=a.id and val not in (min(a.val),max(a.val)) order by val) else
'' end
+case when count(*)=4 then ','+(select top 1 val from test where
id=a.id and val not in (min(a.val),max(a.val)) order by val desc)
else '' end
+case when count(*)=3 then ','+(select val from test where id=a.id
and val not in (min(a.val),max(a.val))) else '' end
+case when count(*)>=2 then ','+max(val) else '' end as
val
from
group
运行结果:
id
-----------
------------------------------------------------------
1
2
3
4
注意:该种方法存在一定的局限性,当每组的记录数变化时,需要手动拼接对应的SQL语句处理。如你的需求数据中每组数据多余4条记录时,请采用其他相对灵活的方法处理。
5、使用自带函数STUFF()和OUTER
APPLY来处理
注意:由于函数OUTER APPLY在SQL
SERVER2005及以上版本数据库中才存在,所以下面的方法只适用于SQL SERVER2005及以上。
select
from
(
select
from
)a
OUTER APPLY
(
select val=stuff(replace(replace((select val from test N where
id=a.id for xml auto),'',''),1,1,'')
)b
运行结果:
id
----------- -----------------------------------
1
2
3
4
6、通过循环生成处理
declare
declare
insert
select
from
declare
select
while
begin
select
declare
set
select
--select stuff(@str,1,1,'')
insert
select
set
end
select
运行结果:
id
----------- ------------------------------
1
2
3
4
本文参考资料:http://www.360doc.com/content/13/0520/10/1485725_286711747.shtml