求一条sql文

Phoenix_99 2009-10-21 10:03:44
TT1

name rdate rodate price1 vdate vodate price2

A 2008-02-03 2008-04-03 2 2008-02-03 2008-04-03 1

A 2008-04-03 2008-05-23 4 2008-04-03 3


A 2008-05-23 2008-06-03 6


A 2008-06-03 8



TT2

name pdate podate price3

A 2008-01-01 13






要查询结果为

name price1 price2 price3

A 6 3 13

条件是查询TT1表里时间位于2008-05-23 到 2008-06-03里的price1的数据,同时取price2的数据,如果为空,就取它上一次的数据,和TT2关连也是取这个时间段的price3的数据,如果没有,也取它上一次的数据。
...全文
92 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
小灰狼W 2009-10-21
  • 打赏
  • 举报
回复
with tt1 as(select 'A' name,'2008-02-03' rdate,'2008-04-03' rodate,2 price1,'2008-02-03' vdate,'2008-04003' vodate,1 price2 from dual
union all select 'A','2008-04-03','2008-05-23',4,'2008-04-03',null,3 from dual
union all select 'A','2008-05-23','2008-06-04',6,null,null,null from dual
union all select 'A','2008-06-03',null,8,null,null,null from dual)
,tt2 as(select 'A' name,'2008-01-01' pdate,null podate,13 price3 from dual)

select * from(
select tt1.name,tt1.rodate,decode(tt1.price1,null,lag(tt1.price1)over(order by
case when tt1.rdate<='2008-05-25' and (tt1.rodate>'2008-05-25' or tt1.rodate is null) then '2008-05-25' when tt1.price1 is null then '2020' else tt1.rdate end ),tt1.price1)price1,
decode(tt1.price2,null,lag(tt1.price2)over(order by
case when tt1.rdate<='2008-05-25' and (tt1.rodate>'2008-05-25' or tt1.rodate is null) then '2008-05-25' when tt1.price2 is null then '2020' else tt1.rdate end ),tt1.price2)price2
,tt2.price3
from tt1,tt2
where tt1.name=tt2.name
and tt1.rdate<='2008-05-25')
where rodate>'2008-05-25'

用你的实际数据替换掉'2008-05-25'
Phoenix_99 2009-10-21
  • 打赏
  • 举报
回复
条件是rodate is null 同时 大于rdate的话,就取price1,或者输入的时间大于rdate同时小于rodate的话,也取price1,同理取price2的值,和TT2关连是通过name关连的,TT2中没有重复的值,在tt2中price3的值,同样是取price1的道理
gelinqing 2009-10-21
  • 打赏
  • 举报
回复
union+case when ?
iqlife 2009-10-21
  • 打赏
  • 举报
回复
更完整的问题信息....
小灰狼W 2009-10-21
  • 打赏
  • 举报
回复
2008-05-23 2008-06-03 指的是rdate rodate ?
如果为空,就按rdate rodate 的时间顺序取上一条记录的值?
tt1和tt2通过什么关联?如果按name关联的话,tt2中有多条name相同的值怎么办
tt2看着像是tt1的一部分..

17,089

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧