我有一个看起来像这样的表:
ID Name
1 John
1 Maria
1 Sam
2 Lisa
2 Martin
我想有这样的输出:
ID NAME1 NAME2 NAME3
1 John Maria Sam
2 Lisa Martin NULL
我不想使用pivot
功能,因为它不会给我这个结果(尝试时)。
ID
只生成3行id
nr,因此只有3个名称列。
为此查询完成SP:
INSERT INTO [Database].[dbo].[TEST]
(
[ID],
[Contact1],
[Contact2],
[Contact3]
)
;WITH CTE
AS
(
SELECT
ID,
NAMN,
ROW_NUMBER() OVER(PARTITION BY P_ID ORDER BY NAMN) AS RowNum
FROM tabl1
WHERE VISA_EJ = 0
)
SELECT
[ID],
[1] AS [Contact1],
[2] AS [Contact2],
[3] AS [Contact3]
FROM CTE
PIVOT(MAX(NAMN) for RowNum in ([1],[2],[3])) AS [Contacts]
分号仍然出错。
答案 0 :(得分:2)
您可以使用窗口功能和旋转的组合:
;with cte as(select id,
name,
row_number() over(partition by id order by name) as rn
from table_name)
select id,
[1] as name1,
[2] as name2,
[3] as name3
from cte
pivot(max(name) for rn in([1],[2],[3]))p
或者您可以使用子查询执行相同的操作:
select id,
[1] as name1,
[2] as name2,
[3] as name3
from (select id,
name,
row_number() over(partition by id order by name) as rn
from table_name) cte
pivot(max(name) for rn in([1],[2],[3]))p
修改强>
;WITH CTE
AS
(
SELECT
ID,
NAMN,
ROW_NUMBER() OVER(PARTITION BY P_ID ORDER BY NAMN) AS RowNum
FROM tabl1
WHERE VISA_EJ = 0
)
INSERT INTO [Database].[dbo].[TEST]
(
[ID],
[Contact1],
[Contact2],
[Contact3]
)
SELECT
[ID],
[1] AS [Contact1],
[2] AS [Contact2],
[3] AS [Contact3]
FROM CTE
PIVOT(MAX(NAMN) for RowNum in ([1],[2],[3])) AS [Contacts]
答案 1 :(得分:1)
这个现在工作:
WITH ot AS (
SELECT ID, Name,
ROW_NUMBER() OVER (Partition BY ID ORDER BY Name) n
FROM tbl )
SELECT a.id id, a.Name name1,b.Name name2, c.Name name3
FROM ot a
LEFT JOIN ot b ON b.id=a.id AND b.n=2
LEFT JOIN ot c ON c.id=b.id AND c.n=3
WHERE a.n=1
ORDER BY id
见这里:http://sqlfiddle.com/#!6/2f850/1
这将仅显示列name2和name3。