我有Oracle 12c,因此请根据使用Oracle语法的答案。我想将多行数据合并为1行。请查看示例的预期结果。我尝试使用PIVOT函数,但对我而言不起作用,因为我想将PIVOT Call_day从上一行移至最新行,并希望获得列的列表,如下面的“预期结果”所示。谢谢您的帮助。
表中的数据:
Acct_num Call_day Call_code Start_day_To_Call
1 04/23/2018 AA 04/02/2018
1 04/24/2018 NULL 04/02/2018
1 04/25/2018 CC 04/02/2018
2 04/26/2018 ZZ 05/02/2018
2 04/27/2018 CC 05/02/2018
如果在Start_day_To_Call日期内进行了多次通话,那么我想要最近2个最近的通话数据,如下所示:
预期结果:
Acct_num Call_day1 Call_day2 Call_code1 Call_code2 Start_day_To_Call
1 04/24/2018 04/25/2018 NULL CC 04/02/2018
2 04/26/2018 04/27/2018 ZZ CC 05/02/2018
答案 0 :(得分:0)
如果只需要两天,则可以使用以下查询:
首先,您要获得每个acct_num的最后一次调用,然后找到上一个调用,然后根据它们填充数据。您可以根据需要使用ID来提高效果。
select p.acct_num,
p.prev_last_day,
(select z.call_code
from test_tbl z
where z.acct_num = p.acct_num
and z.call_day = p.prev_last_day) prev_call_code,
last_day,
(select z.call_code
from test_tbl z
where z.acct_num = p.acct_num
and z.call_day = p.last_day) last_call_code,
p.start_day_to_call
from (select x.acct_num,
max(x.call_day) last_day,
max((select max(y.call_day)
from test_tbl y
where y.acct_num = x.acct_num
and y.call_day < x.call_day)) prev_last_day,
min(x.start_day_to_call) start_day_to_call
from test_tbl x
group by x.acct_num) p
order by p.acct_num