仅将几行转换为 SQL 中的列
Convert only few Rows to Columns in SQL
我只想将 table 中的 2 列转换为行,在 SQL 中有 6 列,如下所示。可能吗?我已尝试 PIVOT
,但它没有按预期工作。
这是我的 table:
-------------------------------------------------
| ID | Contact | DESC_ID | DESCRIPT | VALUE |
-------------------------------------------------
| 22 | 55555 | 1 | Name | Vijay |
| 22 | 55555 | 2 | Country | India |
| 22 | 55555 | 3 | State | Maha |
| 22 | 55555 | 4 | Location | Mumbai |
| 22 | 55555 | 5 | Color | Brown |
-------------------------------------------------
我正在尝试创建以下结果:
--------------------------------------------------------------------
| ID | Contact | Name | Country | State | Location | Color |
--------------------------------------------------------------------
| 22 | 55555 | Vijay | India | Maha | Mumbai | Brown |
--------------------------------------------------------------------
这个怎么查询。可能吗?
create Table Table1 (ID int, Contact int, DESC_ID int, DESCRIPT varchar(100), VALUE varchar(100));
insert into Table1(ID,Contact ,DESC_ID,DESCRIPT,VALUE)
values( 22 , 55555 , 1 , 'Name' , 'Vijay' )
, (22 , 55555 , 2 , 'Country' , 'India' )
,( 22 , 55555 , 3 , 'State' , 'Maha' )
, (22 , 55555 , 4 , 'Location' , 'Mumbai' )
,( 22 , 55555 , 5 , 'Color' , 'Brown')
select * from
(
select ID,Contact,VALUE,DESCRIPT from table1
) d
pivot (
max(VALUE) for DESCRIPT in (Name,Country,State,Location,Color)
) piv
我只想将 table 中的 2 列转换为行,在 SQL 中有 6 列,如下所示。可能吗?我已尝试 PIVOT
,但它没有按预期工作。
这是我的 table:
-------------------------------------------------
| ID | Contact | DESC_ID | DESCRIPT | VALUE |
-------------------------------------------------
| 22 | 55555 | 1 | Name | Vijay |
| 22 | 55555 | 2 | Country | India |
| 22 | 55555 | 3 | State | Maha |
| 22 | 55555 | 4 | Location | Mumbai |
| 22 | 55555 | 5 | Color | Brown |
-------------------------------------------------
我正在尝试创建以下结果:
--------------------------------------------------------------------
| ID | Contact | Name | Country | State | Location | Color |
--------------------------------------------------------------------
| 22 | 55555 | Vijay | India | Maha | Mumbai | Brown |
--------------------------------------------------------------------
这个怎么查询。可能吗?
create Table Table1 (ID int, Contact int, DESC_ID int, DESCRIPT varchar(100), VALUE varchar(100));
insert into Table1(ID,Contact ,DESC_ID,DESCRIPT,VALUE)
values( 22 , 55555 , 1 , 'Name' , 'Vijay' )
, (22 , 55555 , 2 , 'Country' , 'India' )
,( 22 , 55555 , 3 , 'State' , 'Maha' )
, (22 , 55555 , 4 , 'Location' , 'Mumbai' )
,( 22 , 55555 , 5 , 'Color' , 'Brown')
select * from
(
select ID,Contact,VALUE,DESCRIPT from table1
) d
pivot (
max(VALUE) for DESCRIPT in (Name,Country,State,Location,Color)
) piv