[英]How to select multiple existing column names and group it into 1 column?
我正在使用 posgresql。 如何將列名分組到一個列中,並將其值分組到現有表的另一列中? 然后用它來創建臨時表?
現有表:
+---------+----------+---------+----------+
| col_a | col_b | col_c | col_d |
+---------+----------+---------+----------+
| 1 | 2 | 3 | 4 |
+---------+----------+---------+----------+
臨時表:
+----------+----------+
|categories| value |
+----------+----------+
| col_a | 1 |
| col_b | 2 |
| col_c | 3 |
| col_d | 4 |
+----------+----------+
下面是生成臨時表的sql語句。
CREATE TEMPORARY table myTable_temp
(
categories Varchar (50),
value float8
);
但我仍然堅持嘗試將特定列名分組到一列並將其值帶到另一列但仍將其鏈接在一起。
這個過程也稱為 UNPIVOT,可以在 Postgres 中這樣完成:
select up.*
from the_table
cross join lateral (
values
('col_a', col_a),
('col_b', col_b),
('col_c', col_c),
('col_d', col_d)
) as up(category, value);
請注意,這僅適用於所有列具有相同數據類型的情況。
如果您不介意丟失數據類型(或者如果列具有不同的類型並且無論如何您都需要將它們轉換為text
),您可以使用 JSON 函數來實現此動態:
select up.*
from the_table tt
cross join lateral jsonb_each_text(to_jsonb(tt)) as up;
如果您知道所有值都可以轉換為同一類型,則可以使用:
select up.category,
up.value::float
from the_table tt
cross join lateral jsonb_each_text(to_jsonb(tt)) as up(category, value);
在線示例: https://rextester.com/SHOY36906
如果您需要將“值”列與表的原始主鍵匹配,您可以執行以下操作(假設主鍵名為id
)
select tt.id, up.*
from the_table tt
cross join lateral jsonb_each_text(to_jsonb(tt) - 'id') as up(category, value)
order by tt.id;
你只想要一個工會
Select "col_a" , col_a as "value" from
table
union
Select "col_b" , col_b as "value" from
table
union
Select "col_c" , col_c as "value" from
table
union
Select "col_d" , col_d as "value" from
table
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.