转置列 Oracle sql
Posted
技术标签:
【中文标题】转置列 Oracle sql【英文标题】:Transpose columns Oracle sql 【发布时间】:2021-06-29 12:27:47 【问题描述】:我们在下面的结构中有一个 oracle 表。
要求是创建一个 sql 以生成以下格式的报告。 如您所见,最近 6 个月的曝光应该转置为行。 在某些情况下,我们还缺少需要处理的年份和月份数据。 感谢您检查并提出建议。
谢谢, 普拉迪普。
【问题讨论】:
【参考方案1】:使用 lag()
。 . .使用窗口函数获取最后一行:
select pa.*
from (select pa.*,
lag(exposure, 1) over (partition by dealid order by rundate) as exposure_1,
lag(exposure, 2) over (partition by dealid order by rundate) as exposure_2,
lag(exposure, 3) over (partition by dealid order by rundate) as exposure_3,
lag(exposure, 4) over (partition by dealid order by rundate) as exposure_4,
lag(exposure, 5) over (partition by dealid order by rundate) as exposure_5,
row_number() over (partition by dealid order by rundate desc) as seqnum
from poolagreements pa
) pa
where seqnum = 1;
【讨论】:
感谢戈登的建议。我尝试了以下没有任何运气.. 出现 ORA-00933 错误。你能检查和建议吗? select t.* from (select t.*, lag(exposure, 1) over (partition by dealid order by rundate) as exposure_1, lag(exposure, 2) over (partition by dealid order by rundate) as exposure_2, row_number() over (partition by dealid order by rundate desc) as seqnum from poolagreements t ) poolagreements t where seqnum = 1; @Prdp 。 . .表名应该在question 中。假设是poolagreements
,我更新了答案。以上是关于转置列 Oracle sql的主要内容,如果未能解决你的问题,请参考以下文章