我有以下虚拟代码(您可以使用它来测试):
USE tempdb;
GO
CREATE TABLE dbo.Products
(
ProductID VARCHAR (50),
Period VARCHAR (6),
Value DECIMAL (15, 2)
);
INSERT dbo.Products VALUES
('North', '201201', 100),
('South', '201202', 500);
SELECT ProductID, Period, Value
FROM dbo.Products AS p;
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Period)
FROM (SELECT p.Period FROM dbo.Products AS p
GROUP BY p.Period) AS x;
SET @sql = N'
SELECT *
FROM
(
SELECT ProductID, Period, Value
FROM dbo.Products AS p
) AS j
PIVOT
(
SUM(Value) FOR Period IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;
DROP TABLE dbo.Products
它生成输出,但包含 NULL——尽管存在列标题。
要删除 NULL,我的代码现在如下所示:
USE tempdb;
GO
CREATE TABLE dbo.products
(
ProductID VARCHAR (50),
Period VARCHAR (6),
Value DECIMAL (15, 2)
);
INSERT dbo.products VALUES
('North', '201201', 100),
('South', '201202', 500);
SELECT ProductID, Period, Value
FROM dbo.products AS p;
DECLARE @columns NVARCHAR(MAX), @selectList NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Period)
FROM (SELECT p.Period FROM dbo.products AS p
GROUP BY p.Period) AS x;
SET @selectList = N'';
SELECT @selectList += N', ISNULL(' + QUOTENAME(Period) + ', 0)'
FROM (SELECT p.Period FROM dbo.products AS p
GROUP BY p.Period) AS x;
PRINT '@selectList = ' + @selectList
SET @selectList = STUFF(@selectlist, 1, 1, '');
SET @sql = N'
SELECT ProductId, ' + @selectList + '
FROM
(
SELECT ProductID, Period, Value
FROM dbo.products AS p
) AS j
PIVOT
(
SUM(Value) FOR Period IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT '@sql = ' + @sql;
EXEC sp_executesql @sql;
但是现在我的列标题显示[没有列名]?
如何找回标题?