简体   繁体   中英

TSQL Un-pivot 2 columns

Good afternoon stackoverflow.

I need help with pivoting some data. I have tried looking up how to do it on the internet but not had any luck.

I have 4 columns (a,b,c,d) and one row of data.

I would like the data to have 2 columns with 4 rows.

a b c d
1 2 3 4

to become

a 1
b 2
c 3
d 4

SQL fiddle here http://sqlfiddle.com/#!6/68b32/280

Thank you for your time

SELECT letter, val
FROM @t
unpivot(val for letter in (a,b,c,d)) as unpvt

SQL Fiddle

What you are looking for is unpivot

Try this - tested in sql-server-2012:

DECLARE @t TABLE
(
    a int,
    b int,
    c int,
    d int
) 

INSERT INTO @t
SELECT 1,2,3,4

select 
  unpvt.colName
, unpvt.colVal
from (
   select
     a
   , b
   , c
   , d
   from @t
) p
UNPIVOT (colVal FOR colName IN (a, b, c, d) ) as unpvt

Results:

colName colVal
a   1
b   2
c   3
d   4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM