如何将具有不同值的行转换为列?

时间:2016-08-10 12:39:30

标签: sql sql-server

我有一个临时表table1,如下所示

table1
+------+---------------+------------+
| Id   |  Description  |  Attribute |
+------+---------------+------------+
|  1   |    blue       |     color  |
|  1   |    Large      |     size   |
|  1   |    active     |    status  |
|  2   |   green       |    color   |
|  2   |    small      |    size    |
|  2   |    inactive   |   status   |
+------+---------------+------------+

我想返回一张表格,如下所示:

+------+-----------+-----------+-----------+
| Id   |  Color    |   Size    |   Status  |
+------+-----------+-----------+-----------+
|   1  |   blue    |   large   |  active   |
|   2  |  green    |   small   |  inactive |
+------+-----------+-----------+-----------+

有办法做到这一点吗? 谢谢。

4 个答案:

答案 0 :(得分:1)

使用PIVOT,如下所示:

DECLARE @Tbl TABLE (Id INT, Description NVARCHAR(max), Attribute NVARCHAR(50))
INSERT INTO @Tbl
select 1  ,   'blue',        'color' union all
select 1  ,   'Large',       'size' union all
select 1  ,   'active',     'status' union all
select 2  ,   'green',       'color' union all
select 2  ,   'small',      'size ' union all   
select 2  ,   'inactive',  'status' 


SELECT
*
FROM
(
    SELECT * 
    FROM 
        @Tbl
) A 
PIVOT
(
    MIN(Description) 
    FOR 
    Attribute IN ([color], [size], [status]  )
) B

结果:

Id  color   size    status
1   blue    Large   active
2   green   small   inactive

答案 1 :(得分:0)

尝试使用

Select a.id, (select max(b.description) from table1 b where b.id=a.id and b.attribute='color') color,
(select max(c.description) from table1 c where c.id=a.id and c.attribute='size') size,
(select max(d.description) from table1 d where d.id=a.id and d.attribute='status') status
  from table1 a group by a.id

答案 2 :(得分:0)

还没有运行它,但是根据您的要求,这应该可行。但是如果你有更多的属性,那么你应该去动态支点。

select 
case when c.id is not null then c.id 
    when s.id is not null then s.id
    else st.id  end as id
,c.color as color
,s.size as size
,st.status as status
from
 (select id,description as color from table1 where attribute='color') c
full outer join
 (select id,description as Size from table1 where attribute='size') s
on c.id=s.id
full outer join
 (select id,description as status from table1 where attribute='status') st
on c.id=st.id

答案 3 :(得分:0)

PIVOT很简单:

SELECT *
FROM table1
PIVOT
(MAX(Description) FOR Attribute IN (Color, Size, Status)) Pvt