我想将以下行结果转置为列。我当时在考虑PIVOT,但我不相信我能达到预期的效果。
原样:
ID_NCM | DESTINATION | START | END
36393 | PE | 01-01-2018 | 10-31-2018
36393 | PE | 11-01-2018 | 12-31-9999
成为:
ID_NCM | DESTINATION | CURRENT_START | CURRENT_END | FUTURE_START | FUTURE_END
36393 | PE | 01-01-2018 | 10-31-2018 | 11-01-2018 | 12-31-9999
我在这里是否缺少一些表结构概念,从而无法通过select语句实现所需的布局?
谢谢。
答案 0 :(得分:1)
您可以尝试这样-
select id_ncm,
destination,
max(decode(myrank, 1, start_date)) current_start,
max(decode(myrank, 1, end_date)) current_end,
max(decode(myrank, 2, start_date)) future_start,
max(decode(myrank, 2, end_date)) future_end
from (select id_ncm,
destination,
start_date,
end_date,
rank() over(partition by id_ncm order by start_date, end_date) myrank
from your_table) v1
group by id_ncm, destination
答案 1 :(得分:1)
您可以直接将grouping by ID_NCM,DESTINATION
与min
和max
一起使用:
with t(ID_NCM,DESTINATION,"START","END") as
(
select 36393,'PE',date'2018-01-01',date'2018-10-31' from dual union all
select 36393,'PE',date'2018-01-11',date'9999-12-31' from dual
)
select ID_NCM,DESTINATION,
min("START") as CURRENT_START,min("END") as CURRENT_END,
max("START") as FUTURE_START,max("END") as FUTURE_END
from t
group by ID_NCM,DESTINATION
ID_NCM DESTINATION CURRENT_START CURRENT_END FUTURE_START FUTURE_END
------ ----------- ------------- ------------ ------------ -----------
36393 PE 01.01.2018 31.10.2018 11.01.2018 31.12.9999
P.S。 START
和END
是Oracle
中的保留关键字,因此请用双引号将它们引起来。
编辑:由于您的最新评论,您可以通过添加相关子查询来进行更改,如下所示:
with t(ID_NCM,DESTINATION,"START","END",tax_rate) as
(
select 36393,'PE',date'2018-01-01',date'2018-10-31',0.06 from dual union all
select 36393,'PE',date'2018-01-11',date'9999-12-31',0.04 from dual
)
select ID_NCM,DESTINATION,
min("START") as CURRENT_START,min("END") as CURRENT_END,
max("START") as FUTURE_START,max("END") as FUTURE_END,
(select tax_rate from t where "START"=date'2018-01-01' and "END"=date'2018-10-31')
as current_rate,
(select tax_rate from t where "START"=date'2018-01-11' and "END"=date'9999-12-31')
as future_rate
from t
group by ID_NCM,DESTINATION
ID_NCM DEST CURRENT_START CURRENT_END FUTURE_START FUTURE_END CURRENT_RATE FUTURE_RATE
------ ----- ------------- ------------ ------------ ----------- ----------- -----------
36393 PE 01.01.2018 31.10.2018 11.01.2018 31.12.9999 0,06 0,04