标签:style blog http color 数据 2014
1 IF OBJECT_ID(‘TEMPDB..#TEMP‘)>0 2 DROP TABLE #TEMP 3 GO 4 IF OBJECT_ID(‘TEMPDB..#TEMP2‘)>0 5 DROP TABLE #TEMP2 6 GO 7 8 --模拟数据 9 SELECT *INTO #TEMP FROM ( 10 SELECT ‘A‘ col1,‘B‘ col2,‘C‘ col3,‘1‘ X,‘2‘Y,‘3‘Z 11 UNION ALL 12 SELECT ‘A‘ A,‘B‘ B,‘C‘ C,‘4‘ X,‘5‘Y,‘6‘Z 13 UNION ALL 14 SELECT ‘A‘ A,‘B‘ B,‘C‘ C,‘7‘ X,‘8‘Y,‘9‘Z 15 UNION ALL 16 SELECT ‘D‘ A,‘E‘ B,‘F‘ C,‘1‘ X,‘2‘Y,‘3‘Z 17 UNION ALL 18 SELECT ‘D‘ A,‘E‘ B,‘F‘ C,‘4‘ X,‘5‘Y,‘6‘Z 19 UNION ALL 20 SELECT ‘D‘ A,‘E‘ B,‘F‘ C,‘7‘ X,‘8‘Y,‘9‘Z 21 UNION ALL 22 SELECT ‘G‘ A,‘H‘ B,‘I‘ C,‘1‘ X,‘2‘Y,‘3‘Z 23 UNION ALL 24 SELECT ‘G‘ A,‘H‘ B,‘I‘ C,‘4‘ X,‘5‘Y,‘6‘Z 25 UNION ALL 26 SELECT ‘G‘ A,‘H‘ B,‘I‘ C,‘7‘ X,‘8‘Y,‘9‘Z)USB 27 SELECT *FROM #TEMP 28 --分组合并 29 SELECT USB.col1,USB.col2,USB.col3 30 ,LEFT(xxx,LEN(XXX)-1)‘XXX‘ 31 INTO #TEMP2 32 FROM ( 33 SELECT col1,col2,col3 34 ,(SELECT X+‘,‘+Y+‘,‘+Z+‘,‘ FROM #TEMP T1 35 WHERE T1.col1=T2.col1 36 AND t1.col2=t2.col2 37 AND t1.col3=t2.col3 38 FOR XML PATH(‘‘))AS ‘xxx‘ 39 FROM #TEMP T2 40 GROUP BY T2.col1,T2.col2,T2.col3)USB 41 SELECT * FROM #TEMP2 42 --分列处理 43 DECLARE @SQL NVARCHAR(2000),@I INT 44 SET @I=1 45 WHILE EXISTS(SELECT 1 FROM #TEMP2 WHERE XXX<>‘‘) 46 BEGIN 47 SET @SQL=‘ALTER TABLE #TEMP2 ADD 字段‘+CONVERT(VARCHAR,@I)+‘ VARCHAR(20)‘ 48 EXEC(@SQL) 49 SET @SQL=‘declare @loc int update #temp2 set @loc=charindex(‘‘,‘‘,xxx),字段‘ 50 +convert(varchar,@i)+‘=convert(int,case @loc when 0 then xxx else ‘ 51 +‘substring(xxx,1,@loc-1) end),xxx=case @loc when 0 then ‘‘‘‘ else ‘ 52 +‘substring(xxx,@loc+1,len(xxx)-@loc) end where xxx<>‘‘‘‘‘ 53 EXEC(@SQL) 54 SET @I=@I+1 55 END 56 ALTER TABLE #TEMP2 DROP COLUMN XXX 57 --结果 58 SELECT *FROM #TEMP2
效果图预览:
标签:style blog http color 数据 2014
原文地址:http://www.cnblogs.com/sp-oh-dear/p/3794336.html