提问人:phali 提问时间:11/7/2023 最后编辑:SelVaziphali 更新时间:11/7/2023 访问量:34
将多列分成行
Multiple columns into rows
问:
我需要什么查询才能更改结果
从
键值 | 属性1 | 值1 | 属性2 | 值2 | 属性3 | 值3 | 属性4 | 值4 |
---|---|---|---|---|---|---|---|---|
12345 | 美国广播公司 | 54321 | def | 是的 | GHI指数 | 不 | JKL公司 | 67890 |
**自**
键值 | 属性 | 价值 |
---|---|---|
12345 | 属性1 | 值1 |
12345 | 属性2 | 值2 |
12345 | 属性3 | 值3 |
12345 | 属性4 | 值4 |
这是我对第一个表的查询
select key value, attribute1, value 1, attribute2, value2, attribute3, value3, attribute4, value4, attribute5, value5
from tableA
我使用了 UNION ALL,但它显着减慢了该过程,因此我不想使用 UNION ALL。
答:
0赞
JuSun Lee
11/7/2023
#1
其他方式(ORACLE):
select a.key_value
, (
case
when b.rno = 1 then a.Attribute1
when b.rno = 2 then a.Attribute2
when b.rno = 3 then a.Attribute3
when b.rno = 4 then a.Attribute4
end
) as Attribute
, (
case
when b.rno = 1 then a.Value1
when b.rno = 2 then a.Value2
when b.rno = 3 then a.Value3
when b.rno = 4 then a.Value4
end
) as Value
from (
select '12345' as key_value, 'abc' as Attribute1, '54321' as Value1, 'def' as Attribute2, 'Yes' as Value2, 'ghi' as Attribute3, 'No' as Value3, 'jkl' as Attribute4, '67890' as Value4 from dual
) a
cross join (
select 1 as rno from dual
union all
select 2 as rno from dual
union all
select 3 as rno from dual
union all
select 4 as rno from dual
) b
;
0赞
User12345
11/7/2023
#2
您可以尝试使用 .示例代码如下:unnest
-- Create the initial table
CREATE TABLE tableA (
key INT,
attribute1 TEXT,
value1 TEXT,
attribute2 TEXT,
value2 TEXT,
attribute3 TEXT,
value3 TEXT,
attribute4 TEXT,
value4 TEXT
);
-- Insert sample data into the table
INSERT INTO tableA (key, attribute1, value1, attribute2, value2, attribute3, value3, attribute4, value4)
VALUES
(12345, 'abc', '54321', 'def', 'Yes', 'ghi', 'No', 'jkl', '67890'),
(54321, 'xyz', '98765', 'pqr', 'No', 'lmn', 'Yes', 'stu', '12345');
SELECT key ,
unnest(array['attribute1', 'attribute2', 'attribute3', 'attribute4']) AS attribute,
unnest(array[attribute1, attribute2, attribute3, attribute4]) AS value
FROM tableA;
下面是示例小提琴链接
注意:我正在使用基于您的标签的postgreSQL脚本
评论
UNPIVOT