对于我的特定情况,我在使用Pivot查询时遇到了一些困难。 我必须在int列上旋转一个字符串列(所以只有2列) 第三列将保持字符串的串联
Example:
CustomerID Breed
--------------------------
1 Pug
1 Bulldog
1 Doberman
2 Doberman
3 Bulldog
3 Doberman
3 Pug
3 Poedel
Result:
CustomerID Pug Bulldog Doberman Poodle Concat
-----------------------------------------------------------------------------
1 Pug Bulldog Doberman NULL Pug,Bulldog,Doberman
2 NULL NULL Doberman NULL Doberman
3 Pug Bulldog Doberman Poodle Pug,Bulldog,Doberman,Poodle
我尝试过以下帖子中描述的方法: SQL Server: Examples of PIVOTing String data
但这只会在任何地方返回NULL,我猜它是因为我的ID列。
非常感谢任何和所有帮助。
答案 0 :(得分:0)
您可以使用FOR XML PATH
和STUFF连接品种列表。获取带有品种列表的customerID
的查询与此类似:
select customerid, breed,
STUFF((SELECT DISTINCT ', ' + t2.breed
FROM yt t2
WHERE t1.customerid = t2.customerid
FOR XML PATH('')), 1, 1, '') breedList
from yt t1
然后您可以轻松地将此查询合并到PIVOT中:
;with cte as
(
select customerid, breed,
STUFF((SELECT DISTINCT ', ' + t2.breed
FROM yt t2
WHERE t1.customerid = t2.customerid
FOR XML PATH('')), 1, 1, '') breedList
from yt t1
)
select customerid, Pug, Bulldog, Doberman, Poodle, breedList
from cte
pivot
(
max(breed)
for breed in (Pug, Bulldog, Doberman, Poodle)
) piv
order by customerid;
见SQL Fiddle with Demo。这给出了一个结果:
| CUSTOMERID | PUG | BULLDOG | DOBERMAN | POODLE | BREEDLIST |
---------------------------------------------------------------------------------------
| 1 | Pug | Bulldog | Doberman | (null) | Bulldog, Doberman, Pug |
| 2 | (null) | (null) | Doberman | (null) | Doberman |
| 3 | Pug | Bulldog | Doberman | Poodle | Bulldog, Doberman, Poodle, Pug |