感谢让生活变得轻松的测试脚本。
这里有一个关于如何使用 postgresql 进行此操作的想法。
在第一个块中 -> 数据。我尝试获得 id 和 mutate 的所有可能组合 8 次。因此我会得到数据
id num
1 0
1 1
...
1 8
2 0
2..8
之后,在 raw_data 块中,我离开了与 sample_table 中的实际数据的连接,这样我可以保证每个 hrs 0..8 一行
我还根据 (id,hr) 的最早分数对行进行排名 --> rnk
然后我使用 rnk=1 并使用 max(score) over(partition by grp) 得到之前的分数。
然后,我按 id 对数据进行分组,并使用 max 逻辑执行“pivot”,得到预期的输出。
Output
+-----+------+------+------+------+------+------+------+------+------+
| id1 | hr_0 | hr_1 | hr_2 | hr_3 | hr_4 | hr_5 | hr_6 | hr_7 | hr_8 |
+-----+------+------+------+------+------+------+------+------+------+
| 1 | 2765 | 2765 | 2765 | 2765 | 2765 | 1593 | 1593 | 1604 | 1604 |
| 2 | 3500 | 3500 | 2897 | 2897 | 2400 | 2400 | 1647 | 1647 | 1647 |
+-----+------+------+------+------+------+------+------+------+------+
/*
CREATE TABLE sample_table
(
id INT,
hr INT,
tm timestamp,
score INT
);
INSERT INTO sample_table
VALUES (1, 0, '2021-01-21 00:26:45', 2765),
(1, 0, '2021-01-21 00:49:00', 2765),
(1, 5, '2021-01-21 07:47:03', 1593),
(1, 7, '2021-01-21 11:50:48', 1604),
(1, 7, '2021-01-21 12:00:32', 1604),
(2, 0, '2021-01-21 00:50:45', 3500),
(2, 2, '2021-01-21 01:49:00', 2897),
(2, 2, '2021-01-21 05:47:03', 2897),
(2, 4, '2021-01-21 09:30:48', 2400),
(2, 6, '2021-01-21 12:00:32', 1647);
*/
with data
as (select b.id as id
,f as num
from generate_series(0,8) f
join (select distinct id from sample_table) as b
on 1=1
)
,raw_data
as (
select d.id as id1
,d.num as num1
,st.*
,row_number() over(partition by d.id,d.num order by st.tm asc) as rnk
from data d
left join sample_table st
on d.id=st.id
and d.num=st.hr
)
,prep_data
as (select id1
,num1
,max(score) over(partition by id1,grp) as earliest_score
from (select id1,num1,score
,sum(case when score is not null then 1 else 0 end)
over(partition by id1 order by num1) as grp
from raw_data
where rnk=1
)x
)
select id1
,max(case when num1=0 then earliest_score end) as hr_0
,max(case when num1=1 then earliest_score end) as hr_1
,max(case when num1=2 then earliest_score end) as hr_2
,max(case when num1=3 then earliest_score end) as hr_3
,max(case when num1=4 then earliest_score end) as hr_4
,max(case when num1=5 then earliest_score end) as hr_5
,max(case when num1=6 then earliest_score end) as hr_6
,max(case when num1=7 then earliest_score end) as hr_7
,max(case when num1=8 then earliest_score end) as hr_8
from prep_data
group by id1
order by id1;
我尝试在 db-fiddle 上设置脚本,但是对于我使用的 postgresql 查询,它一直在崩溃。
但它确实在 postgresql 数据库中工作,因为我已经在下面运行它并且它工作..
https://extendsclass.com/postgresql-online.html