我使用select case根据条件返回一个值,但是在某些情况下,子查询select会返回多于一行的内容,所以会出现错误。
目标是让函数根据特定条件返回0或1。
SELECT CASE WHEN my_count <= 1 AND stat = "START" THEN 0
WHEN my_count > 1 AND stat IN ("START", "RUN", "ERR") THEN 1
ELSE -1
END AS
INTO return_val
FROM (select
(SELECT count(DISTINCT(stat) FROM my_table
WHERE my_table.HIVE = "hive1"
AND EXTRACT(MONTH FROM PARTITION_DATE) = EXTRACT(MONTH FROM TO_DATE("20190605", 'YYYY-MM-DD'))
AND EXTRACT(YEAR FROM PARTITION_DATE) = EXTRACT(YEAR FROM TO_DATE("20190605", 'YYYY-MM-DD'))
) status_count,
(SELECT DISTINCT(status) AS status_ FROM my_table
WHERE EL_F_BDP_PROC_REALTIME.HIVE = "hive1"
AND EXTRACT(MONTH FROM PARTITION_DATE) = EXTRACT(MONTH FROM TO_DATE("20190605", 'YYYY-MM-DD'))
AND EXTRACT(YEAR FROM PARTITION_DATE) = EXTRACT(YEAR FROM TO_DATE("20190605", 'YYYY-MM-DD'))
)status_
FROM dual
)x ;
RETURN(return_val);
END;
答案 0 :(得分:1)
您在声明中有一些地位:
(SELECT DISTINCT(status) AS status_ FROM my_table
WHERE EL_F_BDP_PROC_REALTIME.HIVE = 'hive1'
AND EXTRACT(MONTH FROM PARTITION_DATE) = EXTRACT(MONTH FROM TO_DATE('20191212', 'YYYY-MM-DD'))
AND EXTRACT(YEAR FROM PARTITION_DATE) = EXTRACT(YEAR FROM TO_DATE('20191212', 'YYYY-MM-DD'))
)
并且返回了多一行。
要执行严格,您需要返回一个值示例:
max((SELECT DISTINCT(status) AS status_ FROM my_table
WHERE EL_F_BDP_PROC_REALTIME.HIVE = 'hive1'
AND EXTRACT(MONTH FROM PARTITION_DATE) = EXTRACT(MONTH FROM TO_DATE('20191212', 'YYYY-MM-DD'))
AND EXTRACT(YEAR FROM PARTITION_DATE) = EXTRACT(YEAR FROM TO_DATE('20191212', 'YYYY-MM-DD'))
))
它正在执行,但是,逻辑可能是错误的
尝试一下:
with tbl as (
select 'START' status, 'hive1' str, to_date('2019-12-11', 'yyyy-mm-dd') dt from dual
union all
select 'NA' status, 'hive1' str, to_date('2019-12-11', 'yyyy-mm-dd') from dual
union all
select 'END' status, 'hive1' str, to_date('2019-12-11', 'yyyy-mm-dd') from dual)
select dt, str, listagg(status, ' ') WITHIN GROUP (ORDER BY str)
from tbl
GROUP BY dt, str
答案 1 :(得分:0)
首先,您的查询有几个语法问题。您需要:
20190605
与YYYY-MM-DD
不兼容)count(DISTINCT(stat)
之后有一个括号缺失如果在case when .. then
之后是as
,则该as
应该跟一个(有效的)别名
我假设my_count
在
status_count
表达式
case..when
是多余的,并且
没有道理因此,请考虑以下SELECT语句:
status_
您与返回多行相关的问题可能是由于部分DISTINCT(status) AS status_
导致的,您可以在其中使用SELECT CASE
WHEN status_count <= 1 AND status_ = 'START' THEN
0
WHEN status_count > 1 AND status_ IN ('START', 'RUN', 'ERR') THEN
1
ELSE
-1
END
INTO :return_val
FROM (SELECT (SELECT COUNT(DISTINCT stat)
FROM my_table
WHERE my_table.HIVE = 'hive1'
AND EXTRACT(MONTH FROM PARTITION_DATE) =
EXTRACT(MONTH FROM DATE'2019-06-05')
AND EXTRACT(YEAR FROM PARTITION_DATE) =
EXTRACT(YEAR FROM DATE'2019-06-05')) status_count,
(SELECT MAX(DISTINCT status)
FROM my_table
WHERE EL_F_BDP_PROC_REALTIME.HIVE = 'hive1'
AND EXTRACT(MONTH FROM PARTITION_DATE) =
EXTRACT(MONTH FROM DATE'2019-06-05')
AND EXTRACT(YEAR FROM PARTITION_DATE) =
EXTRACT(YEAR FROM DATE'2019-06-05')) status_
FROM dual);
或DISTINCT(status) AS status_
之类的聚合来在该子查询中精确返回一行,通过转换为MIN