Pivoting rows into columns in SQL Server

假装没事ソ 提交于 2019-12-04 19:43:25

You can perform with an UNPIVOT. There are two ways to do this:

1) In a Static Unpivot you would hard-code your Field columns in your query.

select firstname
  , lastname
  , replace(field, 'field', '')  as field
  , value
from test
unpivot
( 
  value
  for field in (field1, field2, field3, field27)
) u

See a SQL Fiddle for a working demo.

2) Or you could use a Dynamic Unpivot which will get the list of items to PIVOT when you run the SQL. The Dynamic is great if you have a large amount of fields that you will be unpivoting.

create table mytest
(
  firstname varchar(5),
  lastname varchar(10),
  field1 varchar(1),
  field2 varchar(1),
  field3 varchar(1),
  field27 varchar(1)
)

insert into mytest values('Mark', 'Smith', 'A', 'B', 'C', 'D')
insert into mytest values('John', 'Baptist', 'X', 'T', 'Y', 'G')
insert into mytest values('Tom', 'Dumm', 'R', 'B', 'B', 'U')

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('mytest') and
               C.name like 'Field%'
         for xml path('')), 1, 1, '')

set @query = 'SELECT firstname, lastname, replace(field, ''field'', '''')  as field, value
            from mytest
            unpivot 
            (
               value
               for field in (' + @cols + ')
            ) p '

execute(@query)

drop table mytest

Both will produce the same results.

If you want to do it query than quick and dirty way will be to create Union

             Select FirstName,LastName,1,Field1
             from table
             UNION ALL
             Select FirstName,LastName,2,Field2
             from table
             . 
             .

And similar for all field cols

Rather than using pivot, use unpivot like this:

select firstname, lastname, substring(field,6,2) as field, value
from <yourtablename>
unpivot(value for field in (field1,field2,field3,field4,field5,field6,field7,field8,field9,field10,field11,field12,field13,field14,field15,field16,field17,field18,field19,field20,field21,field22,field23,field24,field25,field26,field27,field1,field2,field3,field4,field5,field6,field7,field8,field9,field10,field11,field12,field13,field14,field15,field16,field17,field18,field19,field20,field21,field22,field23,field24,field25,field26,field27)) as unpvt;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!