我想将包含一列的20行更改为包含20列的1行,以便稍后将其插入第二个数据库
Name
----------
- Frank
- Dora
- ...
- Michael
到
Name1 | Name2 | ... | Name20
Frank | Dora | ... | Michael
我试过
SELECT *
FROM (SELECT TOP 20 firstname AS NAME
FROM database) AS d
PIVOT (Min(NAME)
FOR NAME IN (name1,
name2,
name3,
name4,
name5,
name6,
name7,
name8,
name9,
name10,
name11,
name12,
name13,
name14,
name15,
name16,
name18,
name19,
name20) ) AS f
但所有名字都是NULL
。 DEMO
答案 0 :(得分:1)
你很接近......但你的内部选择必须带有新的列名。试试这样:
DECLARE @tbl TABLE(Name VARCHAR(100));
INSERT INTO @tbl VALUES('Frank'),('Dora'),('Michael');
SELECT p.*
FROM
(
SELECT 'Name' + CAST(ROW_NUMBER() OVER(ORDER BY Name) AS VARCHAR(150)) AS ColumnName
,Name
From @tbl
) AS tbl
PIVOT
(
MIN(Name) FOR ColumnName IN(Name1,Name2,Name3)
) AS p