Oracle SQL:将当前行和前两行的excel嵌套if条件转换为SQL
Posted
技术标签:
【中文标题】Oracle SQL:将当前行和前两行的excel嵌套if条件转换为SQL【英文标题】:Oracle SQL: Convert excel nested if condition on Current row and previous two rows to SQL 【发布时间】:2022-01-05 07:56:57 【问题描述】:我有一个带有嵌套 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
表创建、插入语句和查询在此链接DB<>FIDDLE更新。
感谢任何帮助。提前致谢。
谢谢, 里查
【问题讨论】:
【参考方案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 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小提琴here
【讨论】:
以上是关于Oracle SQL:将当前行和前两行的excel嵌套if条件转换为SQL的主要内容,如果未能解决你的问题,请参考以下文章