我有一个如下查询,它给出了结果集,如图所示
SELECT E1.Name,E1.AccountType ,
STUFF(( SELECT DISTINCT ', ' + CAST(E2.AccountNumber as nvarchar(50))
FROM @temp AS e2
WHERE e1.Name = e2.Name and e1.AccountType = e2.AccountType
FOR XML PATH('')
), 1, 2, '') AS AccountNumber ,
STUFF(( SELECT DISTINCT ', ' + CAST(E2.CustomerNumber as nvarchar(50))
FROM @temp AS e2
WHERE e1.Name = e2.Name and e1.AccountType = e2.AccountType
FOR XML PATH('')
), 1, 2, '') AS CustomerNumber
FROM @temp AS e1
GROUP BY Name,AccountType
现在我想透过这个结果集而不是三行,我的结果集只包含一行,每C,I,T
AccountNumber
个CustomerNumber
三列。
我已经使用单个AccountNumber
列编写了以下查询以进行数据透视,并且该工作对我有用,但我无法了解如何在此数据透视图中包含其他列CustomerNUmber
?
这里是我为单列数据透视表写的查询结果集图像
SELECT * from
(
SELECT E1.Name,E1.AccountType ,
STUFF(( SELECT DISTINCT ', ' + CAST(E2.AccountNumber as nvarchar(50))
FROM @temp AS e2
WHERE e1.Name = e2.Name and e1.AccountType = e2.AccountType
FOR XML PATH('')
), 1, 2, '') AS AccountNumber
FROM @temp AS e1
GROUP BY Name,AccountType
) as src
PIVOT (MAX(AccountNumber) FOR AccountType IN (C,I,T) )AS pvt
已编辑:
答案 0 :(得分:0)
-如果只希望将每个组及其对应的值连接在一起,则无需枢轴操作
SELECT *
FROM (
SELECT E1.[Field_Type]
,STUFF((
SELECT CASE
WHEN E1.[Field_Type] = b.[Field_Type]
THEN ', ' + E2.COLUMN_NAME
END
FROM [DB].[Schema].[Table1] b
INNER JOIN INFORMATION_SCHEMA.COLUMNS E2
ON E2.COLUMN_NAME = b.COLUMN_NAME
FOR XML PATH('')
), 1, 2, '') AS a
FROM [DB].[Schema].[Table1] AS e1
GROUP BY [Field_Type]
) AS src