在oracle中使用LAG表达式

问题描述 投票:0回答:1

我有一栏 (地位) 我想在一个SQL查询中,在一个包含数字和值是1,2或4的表中添加一个计算列 (bitStatus) 将存储当前行和前一行的状态列的位运算器OR。

像这样。

| id | status| bitStatus| 
|----|-------|----------|
| 1  |   1   |   1      |
| 2  |   2   |   3      |
| 3  |   4   |   7      |
| 4  |   1   |   7      |

所以我所做的是在oracle中使用LAG函数,但我不知道如何做,只要我想只在计算的列上创建。位状态

我的查询是这样的。

select id, status, 
BITOR(LAG(bitStatus) OVER (ORDER BY 1), status)) AS bitStatus

但是你知道,我不能在计算bitStatus时使用LAG(bitStatus)。

所以我怎么能让它成为想要的表。

先谢谢你。

oracle lag
1个回答
0
投票

这是否有帮助?

  • 第1-6行代表样本数据
  • TEMP CTE是来取的 LAG 状态值
  • 终极 select 是否 BITOR 作业 bitor(a, b) = a - bitand(a, b) + b

SQL> with test (id, status) as
  2    (select 1, 1 from dual union all
  3     select 2, 2 from dual union all
  4     select 3, 1 from dual union all
  5     select 4, 4 from dual
  6    ),
  7  temp as
  8    (select id, status,
  9                lag(status) over (order by id) lag_status
 10     from test
 11    )
 12  select id,
 13         status,
 14         status - bitand(status, nvl(lag_status, status)) + nvl(lag_status, status) as bitstatus
 15  from temp
 16  order by id;

        ID     STATUS  BITSTATUS
---------- ---------- ----------
         1          1          1
         2          2          3
         3          1          3
         4          4          5

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.