0

I have one table with 25 columns and 1 single row and I want to pivot it and obtain a column with the names of the columns and a column with the corresponding values using SQL. But I do not know how to do it.

I have the following table:

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

And I want to pivot the table and transform the row of the column names into. a column and obtain this:

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

1 Answers1

0

Verbose, but you could use 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;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360