使用 SQL 将具有列名称的行旋转到一列中

Pivot the row with column's names into a column using SQL

我有一个 table 有 25 列和 1 行,我想旋转它 并使用 SQL 获取包含列名称的列和包含相应值的列。但是我不知道怎么做。

我有以下 table:

   +-------+-------+-------+-----+--------+
   | cnt_0 | cnt_1 | cnt_2 | ... | cnt_25 |
   +-------|-------|-------+-----|--------+
   | 34.   |  26   |  15   | ... |  5     |
   +-------+-------+-------+-----+--------+

我想旋转 table 并将列名称的行转换为。一列并获得这个:

   +--------+--------+
   | counts | amount |
   +--------+--------+
   | cnt_0  |  34.   |
   | cnt_1  |  26    |
   | cnt_2  |  15    |
   |  ...   |  ...   |
   | cnt_25 |   5    |
   +--------+--------+

冗长,但您可以使用 UNION ALL:

SELECT counts, amount
FROM
(
    SELECT 'cnt_0' AS counts, cnt_0 AS amount, 0 AS pos UNION ALL
    SELECT 'cnt_1', cnt_1, 1 UNION ALL
    SELECT 'cnt_2', cnt_2, 2 UNION ALL
    ...
    SELECT 'cnt_25', cnt_25, 25
) t
ORDER BY pos;