22,210
社区成员
发帖
与我相关
我的任务
分享
--测试数据
if not object_id('tab') is null
drop table tab
Go
Create table tab(InsertDate DATE, FieldName NVARCHAR(100), FieldValue NVARCHAR(100))
Insert tab
select '2017-9-01', 'FieldName1', 9.1 UNION ALL
select '2017-9-01', 'FieldName2', 9.2 UNION ALL
select '2017-9-01', 'FieldName3', 9.3 UNION ALL
select '2017-9-01', 'FieldName4', 9.4 UNION ALL
select '2017-9-01', 'FieldName5', 9.5 UNION ALL
select '2017-10-01', 'FieldName1', 10.1 UNION ALL
select '2017-10-01', 'FieldName2', 10.2 UNION ALL
select '2017-10-01', 'FieldName3', 10.3 UNION ALL
select '2017-10-01', 'FieldName4', 10.4 UNION ALL
select '2017-10-01', 'FieldName5', 10.5 UNION ALL
select '2017-11-01', 'FieldName1', 11.1 UNION ALL
select '2017-11-01', 'FieldName2', 11.2 UNION ALL
select '2017-11-01', 'FieldName3', 11.3 UNION ALL
select '2017-11-01', 'FieldName4', 11.4 UNION ALL
select '2017-11-01', 'FieldName5', 11.5
DECLARE @name VARCHAR(MAX) ,
@sql VARCHAR(MAX)
SET @name = STUFF(( SELECT DISTINCT
',[' + RTRIM(InsertDate) + ']'
FROM tab
FOR
XML PATH('')
), 1, 1, '')
SET @sql = ''
SET @sql = @sql
+ 'SELECT * from tab pivot(max([FieldValue])for InsertDate in(' + @name
+ '))a'
EXEC( @sql)
--测试数据
if not object_id('tab') is null
drop table tab
Go
Create table tab(InsertDate DATE, FieldName NVARCHAR(100), FieldValue NVARCHAR(100))
Insert tab
select '2017-9-01', 'FieldName1', 9.1 UNION ALL
select '2017-9-01', 'FieldName2', 9.2 UNION ALL
select '2017-9-01', 'FieldName3', 9.3 UNION ALL
select '2017-9-01', 'FieldName4', 9.4 UNION ALL
select '2017-9-01', 'FieldName5', 9.5 UNION ALL
select '2017-10-01', 'FieldName1', 10.1 UNION ALL
select '2017-10-01', 'FieldName2', 10.2 UNION ALL
select '2017-10-01', 'FieldName3', 10.3 UNION ALL
select '2017-10-01', 'FieldName4', 10.4 UNION ALL
select '2017-10-01', 'FieldName5', 10.5 UNION ALL
select '2017-11-01', 'FieldName1', 11.1 UNION ALL
select '2017-11-01', 'FieldName2', 11.2 UNION ALL
select '2017-11-01', 'FieldName3', 11.3 UNION ALL
select '2017-11-01', 'FieldName4', 11.4 UNION ALL
select '2017-11-01', 'FieldName5', 11.5
DECLARE @sql VARCHAR(8000)
SET @sql = 'select FieldName'
SELECT @sql = @sql + ' , max(case InsertDate when ''' + RTRIM(InsertDate)
+ ''' then FieldValue else null end) [' + RTRIM(InsertDate) + ']'
FROM ( SELECT DISTINCT
InsertDate
FROM tab
) AS a
ORDER BY InsertDate
SET @sql = @sql + ' from tab group by FieldName'
EXEC(@sql)