我已将值存储在Fields
表,Name
列中。以下是应作为列名称的名称列表,对于它我使用PIVOT
。我需要将1
添加到所有选定的名称。
它应该是这样的:
枢轴前:
Column name: | Name |
| Jeniffer |
| Jason |
| Jack |
枢轴后:
Column names: | Jennifer1 | Jason1 | Jack1 |
-- It should go as column names
-- And on each of name add 1
我有PIVOT
的代码,它已成功完成,只是问题是如何将单位1
添加到所有选定的值?
这是我的存储过程代码的一部分:
SELECT @cols += ([Name]) + ','
FROM ( SELECT Name -- Here selecting names which should be renamed
FROM Fields
WHERE Id Between 50 And 82
) a
SET @cols = LEFT(@cols, LEN(@cols) - 1)
SET @sql = 'SELECT * FROM
(
SELECT FF.Name AS [NamePiv]
FROM ......................
WHERE ......................
) x
PIVOT
(
MIN (Val1)
FOR NamePiv IN (' + @cols + ')
) p'
EXEC Sp_executesql @sql, N'@param1 NVARCHAR(60), @param2 TINYINT, @param3 NVARCHAR(80)', @param1, @param2, @param3
答案 0 :(得分:0)
您可以创建变量@selectCols
并在其中存储别名:
DECLARE @selectCols varchar(max) = ''
SELECT @cols += ([Name]) + ',', @selectCols += ([Name]) + ' [' + ([Name]) + '1] ,'
FROM ...
SET @selectCols = LEFT(@selectCols, LEN(@selectCols) - 1)
SET @sql = 'SELECT ' + @selectCols + ' FROM
( ...