SQL从行到列的转换

时间:2014-11-20 15:48:06

标签: sql sql-server

我有一张桌子

ID VALUE BRAND
1 group1 Hollister
1 group2 Express
1 group 3 Persche 
2 Group1 Hollister
3 Group3 Persche

等等。并希望转换为类似于sql中唯一ID的内容:

ID Hollister Express Persche 
1  Group1   Group2   Group3 
2  Group1   BLANK    Blank 
3  Blank    Blank    Group3

3 个答案:

答案 0 :(得分:3)

您可以使用pivot或条件聚合:

执行此操作
select id,
       max(case when brand = 'Hollister' then value end) as Hollister,
       max(case when brand = 'Express' then value end) as Express,
       max(case when brand = 'Persche' then value end) as Persche
from table t
group by id;

这将产生NULL。如果你真的想要''

select id,
       max(case when brand = 'Hollister' then value else '' end) as Hollister,
       max(case when brand = 'Express' then value else '' end) as Express,
       max(case when brand = 'Persche' then value else '' end) as Persche
from table t
group by id;

答案 1 :(得分:1)

这是一个有效的PIVOT选项:

Select  * 
From 
(
    Select  value, Brand, id
    From    YourTable
) Source
Pivot
(
    Max(value)
    For Brand In ([Hollister],[Express],[Persche])
) P

答案 2 :(得分:-1)

您可以使用PIVOT和UNPIVOT关系运算符将表值表达式更改为另一个表。

这是一个例子:Convert Rows to columns using 'Pivot' in SQL Server

select *
from 
(
  select store, week, xCount
  from yt
) src
pivot
(
  sum(xcount)
  for week in ([1], [2], [3])
) piv;