日期:2014-05-17 浏览次数:20545 次
USE test
GO
-->生成表tb
if object_id('tb') is not null
drop table tb
Go
Create table tb([ID] smallint,[字段1] nvarchar(1),[字段2] nvarchar(1),[字段3] nvarchar(2),[字段4] nvarchar(1))
Insert into tb
Select 1,N'A',N'B',N'C1',N'D'
Union all Select 2,N'A',N'B',N'C2',N'D'
Union all Select 3,N'A',N'B',N'C3',N'D'
Union all Select 4,N'A',N'B',N'C4',N'D'
Union all Select 5,N'A',N'F',N'C5',N'D'
Union all Select 6,N'A',N'F',N'C6',N'D'
DECLARE @sql NVARCHAR(MAX)
SELECT
@sql=ISNULL(@sql+',','')+'Max(Case when col=''col'+LTRIM(row)+''' Then [字段3] Else '''' End) As [col'+LTRIM(row)+']'
FROM (
SELECT ROW_NUMBER()OVER(PARTITION BY [字段1],[字段2] ORDER BY [字段3]) AS row FROM tb
)AS t
GROUP BY row
EXEC ('
;WITH t AS(
SELECT
*
,''col''+Ltrim(Row_number()over(partition by [字段1],[字段2] ORDER BY [字段3])) As col
FROM tb
)
Select
[字段1]
,[字段2]
,'+@sql+'
,[字段4]
From t
Group by [字段1],[字段2],[字段4]
')
/*
字段1 字段2 col1 col2 col3 col4 字段4
---- ---- ---- ---- ---- ---- ----
A B C1 C2 C3 C4 D
A F C5 C6 D
*/