我正在寻找一种简单的方法来执行此转置:
date ID Vr val
1.1.14 1 2000 50
1.1.14 2 2000 60
1.1.14 2 2001 100
date ID vr2000 vr2001
1.1.14 1 50 0
1.1.14 2 60 100
我有83个变量和超过1米记录的数据。我想结束" vr"到行中的索引变量。有什么建议我怎么办?
答案 0 :(得分:0)
这可以通过使用动态sql查询来完成,并使用sp_executesql存储的precedure执行动态构建的查询。
-- Create table Variable
CREATE TABLE [Variable](
[date] [nvarchar](50) NULL,
[ID] [int] NULL,
[vr] [int] NULL,
[val] [int] NULL
)
--Insert sample records
INSERT [dbo].[Variable] ([date], [ID], [vr], [val])
VALUES (N'1.1.14', 1, 2000, 50),
(N'1.1.14', 2, 2000, 60),
(N'1.1.14', 2, 2001, 100)
GO
--QUERY
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX);
DECLARE @ColumnNamesInPivot AS NVARCHAR(MAX);
DECLARE @ColumnNamesInSelect AS NVARCHAR(MAX);
--Get distinct values of PIVOT Column
SELECT TOP 100 PERCENT
@ColumnNamesInPivot = ISNULL(@ColumnNamesInPivot + ',', '')
+ QUOTENAME(vr),
@ColumnNamesInSelect = ISNULL(@ColumnNamesInSelect + ',', '')
+ 'ISNULL(' + QUOTENAME(vr) + ',0) AS [vr' + CAST(vr AS NVARCHAR(50))
+ ']'
FROM ( SELECT DISTINCT
vr
FROM Variable
) AS P
ORDER BY vr ASC;
--Prepare the PIVOT query using the dynamic query
SET @DynamicPivotQuery = N'Select date,ID,' + @ColumnNamesInSelect + '
FROM ( SELECT *
FROM Variable
) AS SourceTable PIVOT( MAX(val) FOR vr IN (' + @ColumnNamesInPivot
+ ') ) AS PVTTable';
--PRINT @DynamicPivotQuery;
EXEC sp_executesql @DynamicPivotQuery;
结果如下: