在 table 中为每一列创建一行视图

Create view with one row for each column in a table

我有一个 table 看起来像这样:

id | hwerohwsd | dwerwefwf | wfsdwg | fwegwg

1  | 0.867     | 1.5345    | 123.63 | 0.9283
2  | 0.523     | 1.3456    | 341.63 | 3.3495
1  | 0.342     | 1.1467    | 121.63 | 4.9852

我需要一个包含 3 列的视图,原始 table 中的每一列都有一行,所以它看起来像这样:

id | currency | rate
1  | EUR      | 0.867
2  | JPY      | 1.5345
3  | GBP      | 123.63
4  | CHF      | 0.9283

视图中货币列的值需要由我创建(欧元、日元等)并且是固定值; 我需要从原始 table 的第一行获取观看率,忽略所有其他行。

我被困在这个问题上有一段时间了,不知道如何解决这个问题(做了很多研究但没有快乐)。 有人可以帮我吗? 提前致谢!

你在找这个吗?

WITH
-- your input 
indata(id,hwerohwsd,dwerwefwf,wfsdwg,fwegwg) AS (
          SELECT 1,0.867,1.5345,123.63,0.9283
UNION ALL SELECT 2,0.523,1.3456,341.63,3.3495
UNION ALL SELECT 1,0.342,1.1467,121.63,4.9852
)
-- real query starts here, replace following comma with "WITH" ...
,
-- need to pivot four columns in this example:
-- four consecutive integers ...
i(i) AS (
            SELECT 1
  UNION ALL SELECT 2
  UNION ALL SELECT 3
  UNION ALL SELECT 4
)
SELECT
  id  
, i  AS curr_id
 -- currency symbol seems to depend on the position of the input column,
 -- not on the input column name - so hard-wiring i <-> currency symbol correspondence
, CASE i
    WHEN 1 THEN 'EUR'
    WHEN 2 THEN 'JPY'
    WHEN 3 THEN 'GBP'
    WHEN 4 THEN 'CHF'
  END AS currency
, CASE i
    WHEN 1 THEN hwerohwsd
    WHEN 2 THEN dwerwefwf
    WHEN 3 THEN wfsdwg
    WHEN 4 THEN fwegwg
  END AS rate
FROM indata CROSS JOIN i
ORDER BY 1;
-- out  id | curr_id | currency |   rate   
-- out ----+---------+----------+----------
-- out   1 |       1 | EUR      |   0.8670
-- out   1 |       2 | JPY      |   1.5345
-- out   1 |       3 | GBP      | 123.6300
-- out   1 |       4 | CHF      |   0.9283
-- out   1 |       1 | EUR      |   0.3420
-- out   1 |       2 | JPY      |   1.1467
-- out   1 |       3 | GBP      | 121.6300
-- out   1 |       4 | CHF      |   4.9852
-- out   2 |       1 | EUR      |   0.5230
-- out   2 |       2 | JPY      |   1.3456
-- out   2 |       3 | GBP      | 341.6300
-- out   2 |       4 | CHF      |   3.3495

最简单的方法,假设您有另一列,我们可以按 排序(以确定哪一行是 'first') 将是...

WITH
  first_row AS
(
  SELECT *
    FROM your_table
ORDER BY id, something_else
   LIMIT 1
)
          SELECT 1 AS id, 'EUR' AS currency, hwerohwsd AS rate FROM first_row
UNION ALL SELECT 2,       'JPY',             dwerwefwf         FROM first_row
UNION ALL SELECT 3,       'GBP',             wfsdwg            FROM first_row
UNION ALL SELECT 4,       'CHF',             fwegwg            FROM first_row