我正在尝试转换每个 id 具有多行的两个时间戳列的每个人。我想为它们都设置一列而不是行。
timestamp_meaning 告诉我们例如timestamp1 显示的内容 0 - 5 代表机场 1
timestamp_menaing = 0 (0 = airport 1)
时间戳 1:到达机场 1 时间戳 2:从机场 1 出发
我有以下表格结构
ID, timestamp1 timestamp2 timestamp_meaning
1 xx xx 0
1 xx xx 1
1 xx xx 2
2 xx xx 0
2 xx xx 1
3 xx xx 0
(每个id的时间戳含义不同,每个数字代表时间戳的不同含义)
我希望看到的结果如下:
id timestamp1_0, timestamp1_1, timestamp1_2 timestamp1_3 timestamp2_0 timestamp2_1 timestamp2_2, timestamp_2_3
1 xx xx xx NULL XX XX XX
2 xx xx NULL NULL XX XX NULL
3 xx NULL NULL NULL XX NULL
timestamp1_2:其中1是timestamp1列,_2对应timestamp_meaning值。
所以基本上是从行到列的时间戳 1 和时间戳的拆分。
我用时间戳列之一尝试了代码:
select * from table
pivot(listagg(timestamp1) for timestamp_meaning in (0,1,2,3,4,5)) as timestamps
order by ID ;
其中时间戳 1 = 到达 和 timestamp_meaning = 机场 1
当前结果在对角线上
ID 0 1 2 3
1 xx - - -
1 xx
1 xx -
timestamp1:到达时间戳2:离开
我希望结果是每个 id 一行,显示时间戳 1 和时间戳 2 的所有列。我还想将 0,1,2,3 重命名为 airport1_arrival 同样对于timestamp2 airport1_depart
现在它显示机场 1、机场 2 ..... 即 0,1,2,3(在输出中)它确实告诉我它是机场 1,但值不清楚,是否来自到达或离开。
答案 0 :(得分:0)
只需使用条件聚合:
select id,
listagg(case when timestamp_meaning = 0 then timestamp end),
listagg(case when timestamp_meaning = 1 then timestamp end),
listagg(case when timestamp_meaning = 2 then timestamp end),
listagg(case when timestamp_meaning = 3 then timestamp end),
listagg(case when timestamp_meaning = 4 then timestamp end),
listagg(case when timestamp_meaning = 5 then timestamp end)
from table
group by id;