2

我有以下虚拟代码(您可以使用它来测试):

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;

但是现在我的列标题显示[没有列名]?

如何找回标题?

4

1 回答 1

2

下午好!设置 @selectList 变量时,请务必使用“AS”指定列名的别名...

SET @selectList = N'';
SELECT @selectList += N', ISNULL(' + QUOTENAME(Period) + ', 0) AS ' + QUOTENAME(Period)
  FROM (SELECT p.Period FROM dbo.products AS p
  GROUP BY p.Period) AS x;
PRINT '@selectList = ' + @selectList
SET @selectList = STUFF(@selectlist, 1, 1, '');
于 2013-05-19T17:13:12.063 回答