如何用case语句处理单行子查询returns多行错误

How to handle singe-row subquery returns more than one row error with case statement

我正在构建一个涉及 case 语句的 Oracle 查询。

SELECT 
  CASE WHEN 
    ((SELECT agent_or_group_id from trans_slot where slot_id = 
    (SELECT slot_id from trans_slot where slot_alias = 'PP' and measure_expiration > sysdate)) > 0) 
/*The below subquery returns 1 row*/
  THEN (SELECT agent_or_group_id from trans_slot where slot_id = 
    (SELECT slot_id from trans_slot where slot_alias = 'PP' and measure_expiration > sysdate))
  ELSE 
/* The below subquery returns 2 rows*/
   (SELECT child_agent_id FROM agent_object_group_member WHERE parent_agent_id IN
    (SELECT agent_or_group_id FROM trans_slot WHERE slot_id IN
     (SELECT slot_id FROM trans_slot WHERE slot_alias = 'PP' AND measure_expiration > sysdate)
     )
    ) 
END
 "Agent_ID" from DUAL;

当 运行 子查询独立时,它们 运行 很好。但是 运行 宁整个查询 returns

ORA-01427: single-row subquery returns more than one row
01427. 00000 -  "single-row subquery returns more than one row"
*Cause:    
*Action:

如果我明白你在追求什么,你就不能那样做。您需要使用左外连接,然后选择要显示的列值。

这是一个基于您提供的 SQL 的简化示例:

WITH t1 AS (SELECT 1 ID FROM dual UNION ALL
            SELECT 0 ID FROM dual UNION ALL
            SELECT 2 ID FROM dual),
     t2 AS (SELECT 10 child_id, 0 parent_id FROM dual UNION ALL
            SELECT 20 child_id, 0 parent_id FROM dual UNION ALL
            SELECT 30 child_id, 1 parent_id FROM dual UNION ALL
            SELECT 40 child_id, 2 parent_id FROM dual)
---- end of mimicking two tables with the sample data in them. See the query below:
SELECT COALESCE(t2.child_id, t1.id) ID
FROM   t1
       LEFT OUTER JOIN t2 ON (t1.id = t2.parent_id AND t1.id = 0);

        ID
----------
        10
        20
         2
         1

在这里,我使用了 t1 和 t2 子查询来模拟您从原始查询中的主子查询获得的输出。

然后我们仅在 t1.id = 0 的情况下将 t2 外连接到 t1。通过这样做,您可以简单地选择 t2.child_id 值(如果存在),否则使用 t1.id值。

(我知道在你的例子中,t1 等效子查询只会生成 1 行,根据你所说的,但我已经包含了 3 行,这样你就可以看到结果是基于不同的ID。)


预计到达时间:

在您的例子中,我上面示例中的 t1 子查询将是:

SELECT agent_or_group_id
from   trans_slot
where  slot_id = (SELECT slot_id
                  from   trans_slot
                  where  slot_alias = 'PP'
                  and    measure_expiration > sysdate)

并且 t2 子查询将是:

SELECT child_agent_id
FROM   agent_object_group_member
WHERE  parent_agent_id IN (SELECT agent_or_group_id
                           FROM trans_slot
                           WHERE slot_id IN (SELECT slot_id
                                             FROM   trans_slot
                                             WHERE slot_alias = 'PP'
                                             AND measure_expiration > sysdate))