简体   繁体   中英

SQL Server Table Transformation Query / Combine Column Names With Values

This is my existing SQL Table with 3 columns (q1, q2, q3) and 2 rows :

> q1 q2 q3
> --------
> 1  2  3
> 4  5  6

I need an SQL query that would transform that table and return a result set containing 2 new columns (cg, sg) and 6 rows combining table column names with values:

> cg  sg
> ======
> q1  1
> q1  4
> q2  2
> q2  5
> q3  3
> q3  6

Perhaps that would require some kind of "PIVOT" operation, but I can't get it to work after numerous tries.

Any advice or solution? Thanks.

PS I can't use stored procedures, only a single query.

You can do this using UNION:

SELECT 'q1' as cg, q1 as sg FROM t1
UNION SELECT 'q2' as cg, q2 as sg FROM t1
UNION SELECT 'q3' as cg, q3 as sg FROM t1

Here is another method that scans the table only once.

SELECT
   x.*
FROM tbl t
CROSS APPLY( VALUES
    ('q1', q1),
    ('q2', q2),
    ('q3', q3)
) x(cg, sg)

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