1

对于我的特定情况,我在使用 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:PIVOTing String 数据的示例

但这只是到处返回 NULL,我猜这是因为我的 ID 列。

非常感谢任何和所有帮助。

4

1 回答 1

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

请参阅SQL Fiddle with Demo

然后您可以轻松地将此查询合并到 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 |
于 2013-05-24T22:31:06.010 回答