Oracle SQL:将当前行和前两行的嵌套条件 excel 转换为 SQL

Oracle SQL: Convert excel nested if condition on Current row and previous two rows to SQL

我有一个带有嵌套 IF 条件的 excel 公式,它将当前行值与紧邻的前一行以及前一行与来自同一列的前第二行值进行比较。

公式:

=IF(B8<>B7,IF(B7<>B6,B6,B7),B8) 

已尝试以下查询,但出现错误 "ORA-00920: 无效的关系运算符"

select MYTABLE.*,
CASE    WHEN MSYMBOL over (order by MDATE)   <> lag(MSYMBOL,1) over (order by MDATE)
        THEN CASE 
                        WHEN lag(MSYMBOL,1) over (order by MDATE) <> lag(MSYMBOL,2) over (order by MDATE)
                        THEN lag(MSYMBOL,2) over (order by MDATE)
                        ELSE lag(MSYMBOL,1) over (order by MDATE)
             END,
        ELSE MSYMBOL over (order by MDATE)
END as FLAG
from MYTABLE

Table 创建、插入语句和查询在此 link DB<>FIDDLE.

中更新

感谢对此的任何帮助。提前致谢。

谢谢,
里查

  • MSYMBOL over (order by MDATE) 无效,您只想使用 MSYMBOL.
  • 第一个 END.
  • 后多了一个逗号
  • 此外,NULL <> something 永远不是真的,需要考虑到这一点。

您可以使用:

select MYTABLE.*,
       CASE
       WHEN MSYMBOL <> lag(MSYMBOL,1) over (order by MDATE)
       OR   (MSYMBOL IS NULL AND lag(MSYMBOL,1) over (order by MDATE) IS NOT NULL)
       OR   (MSYMBOL IS NOT NULL AND lag(MSYMBOL,1) over (order by MDATE) IS NULL)
       THEN CASE 
            WHEN lag(MSYMBOL,1) over (order by MDATE) <> lag(MSYMBOL,2) over (order by MDATE)
            OR   (lag(MSYMBOL,1) over (order by MDATE) IS NULL AND lag(MSYMBOL,2) over (order by MDATE) IS NOT NULL)
            OR   (lag(MSYMBOL,1) over (order by MDATE) IS NOT NULL AND lag(MSYMBOL,2) over (order by MDATE) IS NULL)
            THEN lag(MSYMBOL,2) over (order by MDATE)
            ELSE lag(MSYMBOL,1) over (order by MDATE)
            END
       ELSE MSYMBOL
       END as FLAG
from   MYTABLE

但你最好将比较反转为使用 =

select MYTABLE.*,
       CASE
       WHEN MSYMBOL = lag(MSYMBOL,1) over (order by MDATE)
       THEN MSYMBOL
       WHEN lag(MSYMBOL,1) over (order by MDATE) = lag(MSYMBOL,2) over (order by MDATE)
       THEN lag(MSYMBOL,1) over (order by MDATE)
       ELSE lag(MSYMBOL,2) over (order by MDATE)
       END as FLAG
from   MYTABLE

输出:

MDATE MSYMBOL FLAG
01-NOV-21
02-NOV-21
03-NOV-21
04-NOV-21
05-NOV-21 Square
06-NOV-21 Circle
07-NOV-21 Circle Circle
08-NOV-21 Circle Circle
09-NOV-21 Square Circle

db<>fiddle here