为此,您必须使用UNPIVOT
表运算符,如下所示:
SELECT col, val
FROM Tablename AS t
UNPIVOT
(
Val
FOR Col IN (T1, T2, ..., T20)
) AS u;
SQL 小提琴演示。
更新 1
如果您想为任意数量的列动态地执行此操作,而无需手动编写它们,我能想到的唯一方法是从表中读取这些列information_schema.columns
以获取表的列名列表。然后使用动态 SQL 来动态组合语句,FOR col IN ...
如下所示:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(column_name)
FROM information_schema.columns
WHERE table_name = 'tablename'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SELECT @query = ' SELECT col, val
FROM tablename AS t
UNPIVOT
(
val
FOR col IN ( ' + @cols + ' )
) AS u;';
EXECUTE(@query);
这会给你:
| COL | VAL |
-------------
| T1 | 1 |
| T10 | 15 |
| T11 | 33 |
| T12 | 31 |
| T13 | 12 |
| T14 | 10 |
| T15 | 12 |
| T16 | 9 |
| T17 | 10 |
| T18 | 2 |
| T19 | 40 |
| T2 | 0 |
| T20 | 21 |
| T3 | 9 |
| T4 | 2 |
| T5 | 3 |
| T6 | 10 |
| T7 | 14 |
| T8 | 15 |
| T9 | 20 |