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

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

提问人:Richa 提问时间:11/28/2021 更新时间:11/28/2021 访问量:75

问:

我有一个带有嵌套 IF 条件的 excel 公式,该公式将当前行值与当前行进行比较,将上一行与同一列的前第二行值进行比较。

公式:

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

enter image description here

尝试了以下查询,但收到错误“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

表创建、插入语句和查询在此链接 DB<>FIDDLE 中更新。

感谢任何帮助。提前致谢。

谢谢,
Richa

SQL Oracle Excel 公式 比较 滞后

评论


答:

1赞 MT0 11/28/2021 #1
  • 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符号
01-十一月,21
02 11月,21
03 11月,21
04 11月,21
05 11月,21 广场
06 11月,21
07 11月,21
08 11月,21
09 11月,21 广场

db<>fiddle 在这里