Sql split函数:
/*分割一定格式的数据源 以数据表的形式返回
*/
CREATE function f_splitstr(@SourceSql varchar(8000),@StrSeprate varchar(10))
returns @temp table(F1 varchar(100))
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>''
insert @temp values(@SourceSql)
return
end
行转列:
select identity(int ,1,1) as rownum1 ,F1 as F1 into #tmp1 from dbo.f_splitstr('1,2,3,4',',')
declare @sql varchar(8000)
set @sql ='select'
select @sql= @sql + ' F1= '+ F1 +',' from #tmp1
set @sql =substring(@sql,0,len(@sql))
exec (@sql)
合并列数
select identity(int ,1,1) as rownum1 ,F1 as F1 into #tmp1 from dbo.f_splitstr('1,2,3,4',',')
select identity(int ,1,1) as rownum2 ,F1 as F2 into #tmp2 from dbo.f_splitstr('A,B,C,D',',')
select F1,F2 from #tmp1 ,#tmp2 where rownum1=rownum2
有效的例子(多行合并)
CREATE TABLE tb(sn varchar(20),process_id int,data_id int,measuredata numeric(9,2))
INSERT tb SELECT '12770006',1,1,1.34
UNION ALL SELECT '12770006',1,2,046
UNION ALL SELECT '12770006',1,3,9.82
UNION ALL SELECT '14061916',2,1,5.5
UNION ALL SELECT '14061916',2,2,4.36
UNION ALL SELECT '12770006',2,1,6.43
UNION ALL SELECT '12770006',2,2,0.12
UNION ALL SELECT '12770006',2,3,6.37
UNION ALL SELECT '14061916',3,1,3.4
UNION ALL SELECT '14061916',3,2,1.1
--查询处理
DECLARE @s nvarchar(4000)
--交叉报表处理代码头
SET @s='SELECT sn,process_id'
--生成列记录水平显示的处理代码拼接(处理Item列)
SELECT @s=@s
+','+QUOTENAME(data_id)
+N'=SUM(CASE data_id WHEN '+QUOTENAME(data_id,N'''')
+N' THEN measuredata END)'
FROM tb
GROUP BY data_id
SELECT sn,process_id,[1]=SUM(CASE data_id WHEN '1' THEN measuredata END),[2]=SUM(CASE data_id WHEN '2' THEN measuredata END),[3]=SUM(CASE data_id WHEN '3' THEN measuredata END)FROM tb GROUP BY sn,process_id
--拼接交叉报表处理尾部,并且执行拼接后的动态SQL语句
EXEC(@s+N'FROM tb GROUP BY sn,process_id')
drop table tb
来源:https://www.cnblogs.com/zcjljww/archive/2007/07/27/833788.html