一个复杂ORACLE查询

xiaoweialien 2009-02-18 03:54:34
表A
Box Position used
1 1 1
1 2 1
1 3 1
2 1 1
2 2 1
2 3 1

表B
Box Position action
1 1 -
1 2 -
2 1 -
2 3 -
1 2 +
1 1 +
1 1 -


查询要求:表A表示初使状态, 表B表示操作历史: -表示used由1变为0,+表示used由0变为1.写一个SQL语句,得出表A现在的状态,也就是经过表B的操作流程后的状态(按照表B顺序操作).
...全文
106 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaoweialien 2009-02-20
  • 打赏
  • 举报
回复
Sorry, 应该是按表B的时间来排序。
表A
Box Position used
1 1 1
1 2 1
1 3 1
2 1 1
2 2 1
2 3 1

表B
Box Position action time
1 1 - 2008-01-02
1 2 - 2008-01-03
2 1 - 2008-01-04
2 3 - 2008-01-05
1 2 + 2008-01-06
1 1 + 2008-01-07
1 1 - 2008-01-08
白发程序猿 2009-02-20
  • 打赏
  • 举报
回复
少写了点东西

select a.box, a.position, decode(nvl(c.action,-2),-2,a.used,a.used + c.action) used
from A,
(select box, position, sum(action) action
from (select box, position, decode(action, '-', -1, 1) action
from B)
group by box, position) C
where a.box = c.box(+)
and a.position = c.position(+)
白发程序猿 2009-02-20
  • 打赏
  • 举报
回复
1楼说的,我一开始也是这样想的
但实际上不用管它的顺序,因为只有两个操作而已,而且是相反的
所以只要一对一对去看是否有剩余的单个操作就行
这样应该是对的吧

select a.box, a.position, decode(nvl(c.action,'-2'),a.used,a.used + c.action) used
from A,
(select box, position, sum(action) action
from (select box, position, decode(action, '-', -1, 1) action
from B)
group by box, position) C
where a.box = c.box(+)
and a.position = c.position(+)

我的思路就是把+看成1,-看成-1,sum后就总共有三个结果,-1,0,1
再与初始的used相加,有4种结果再加上一种没有操作历史的结果
如果A表的数据没有操作过,也就是B表中没有对应的数据,则值为a.used
如果A表的used=0,那么sum后值只能是0,1,相加就会得到二种结果,0,1,则值对应为0,1
如果A表的used=1,那么sum后值只能是-1,0,相加就会得到二种结果,0,1,则值对应为0,1
wqyitian 2009-02-18
  • 打赏
  • 举报
回复
首先你要给出表B的排序规则,或者是order by B.box,B.position 或者是 order by B.modified_datetime,你只说按照B的顺序排,难道你要我们去总结排序规则吗?或者你给的B的例子根本就总结不出规则。

select t1.box,t1.position, (case t2.action when null then 1 when '-' then 0 when '+' then 1 end) as used
from A t1,(select * from B where rownum<2 order by modified_datetime desc) t2
where t1.box=t2.box(+) and t1.position=t2.position(+)


--思路很简单,就是取B最后一次的操作,然后判断A的状态。

3,491

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 高级技术相关讨论专区
社区管理员
  • 高级技术社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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