我有一张这样的表:
id unit
1 mm
2 cm
3 kg
当我对此进行枢轴操作时,我得到的结果如下:
1 2 3
mm cm kg
是否可以在此处获取自定义列名称,如下所示:
d1 d2 d3
mm cm kg
我使用Pivot作为:
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
GO
CREATE table #t
(id varchar(max),unit varchar(max))
insert into #t (id,unit)values
(1,'kg'),
(2,'cm'),
(3,'mm'),
(4,'m')
DECLARE @statement NVARCHAR(max)
,@columns NVARCHAR(max)
SELECT @columns = ISNULL(@columns + ',', '') + N'[' + cast(tbl.id as varchar(max)) + ']'
FROM (
SELECT DISTINCT id
FROM #t
) AS tbl
SELECT @statement = 'select *
INTO ##temp
from (
SELECT id,[unit]
FROM #t
) as s
PIVOT
(max(unit) FOR id in(' + @columns + ')) as pvt
'
EXEC sp_executesql @statement = @statement
SELECT * FROM ##temp
DROP TABLE #t
DROP TABLE ##temp
有可能吗? 感谢
答案 0 :(得分:3)
IF OBJECT_ID('tempdb..#t') IS NOT NULL
DROP TABLE #t
GO
CREATE TABLE #t (
id VARCHAR(10),
unit VARCHAR(100)
)
INSERT INTO #t (id, unit)
VALUES
('1', 'kg'),
('2', 'cm'),
('3', 'mm'),
('4', 'mm')
DECLARE @SQL NVARCHAR(MAX), @columns NVARCHAR(MAX)
SELECT @columns = STUFF((
SELECT ',[D' + id + ']'
FROM #t
FOR XML PATH('')), 1, 1, '')
SELECT @SQL = '
SELECT *
FROM (
SELECT [unit], col = N''D'' + id
FROM #t
) s
PIVOT (MAX(unit) FOR col IN (' + @columns + ')) p'
EXEC sys.sp_executesql @SQL
答案 1 :(得分:2)
只需在您的ID中添加前缀即可。实施例
SELECT @statement = 'select * INTO ##temp from
( SELECT [id] = ''d''+id,[unit] FROM #t ) as s
PIVOT
(max(unit) FOR id in(' + @columns + ')) as pvt '
使用全局临时表也是一种可怕的做法!特别是一个名为## temp
的人答案 2 :(得分:1)
您可以将CASE
表达式与动态SQL查询一起使用。
CREATE TABLE #t
(
id INT,
unit VARCHAR(2)
);
INSERT INTO #t VALUES
(1,'mm'),
(2,'cm'),
(3,'kg');
DECLARE @query AS VARCHAR(MAX);
SELECT @query = 'SELECT ' +
STUFF
(
(
SELECT DISTINCT ',MAX(CASE WHEN id = '+ CAST(id AS VARCHAR(10))
+ ' THEN unit END) AS d' + CAST(id AS VARCHAR(10))
FROM #t
FOR XML PATH('')
),
1,1,'');
SELECT @query += ' FROM #t;';
EXECUTE(@query);
<强>结果强>
+----+----+----+
| d1 | d2 | d3 |
+----+----+----+
| mm | cm | kg |
+----+----+----+
答案 3 :(得分:0)
SELECT @statement = 'select * INTO ##temp from ( SELECT ''d''+id AS [id],[unit] FROM #t ) as s PIVOT (max(unit) FOR id in(' + @columns + ')) as pvt '