子查询作为 CASE WHEN 条件

Posted

技术标签:

【中文标题】子查询作为 CASE WHEN 条件【英文标题】:Subquery as CASE WHEN condition 【发布时间】:2021-09-07 07:22:36 【问题描述】:

以下查询,AS PQ_COUNT 发生语法错误

SELECT CASE WHEN
     RESULTS LIKE '%PQ - Duplicate%' AND 
     (SELECT COUNT(*) FROM MY_TABLE WHERE ID = '998877'AND FINAL_RESULTS='FL_57') AS PQ_COUNT >= 1 
    THEN 'PQ count = '|| PQ_COUNT 
ELSE RESULTS END AS RESULTS 

如果我将AS PQ_COUNT 移动到选择查询中,

(SELECT COUNT(*) AS PQ_COUNT FROM MY_TABLE WHERE ID = '998877'AND FINAL_RESULTS='FL_57') >= 1

THEN 块中 PQ_COUNT 的引用成为无效标识符 (ORA-00904)

将处理时可能会出现什么问题?

【问题讨论】:

【参考方案1】:

一种选择是使用子查询(或 CTE,如我的示例)来计算满足条件的行数,然后 - 因为它只包含一行 - 将其交叉连接到 my_table。像这样的:

SQL> WITH
  2     my_table (id, final_results, results) AS
  3     -- sample data
  4        (SELECT '998877', 'FL_57', 'PQ - Duplicate' FROM DUAL),
  5     cnt AS
  6     -- calculate COUNT first ...
  7        (SELECT COUNT (*) pq_count               --> pq_count
  8           FROM MY_TABLE
  9          WHERE     ID = '998877'
 10                AND FINAL_RESULTS = 'FL_57')
 11  -- ... then re-use it in "main" query
 12  SELECT CASE
 13            WHEN     a.results LIKE '%PQ - Duplicate%'
 14                 AND b.pq_count >= 1            --> reused here
 15            THEN
 16               'PQ count = ' || b.PQ_COUNT      --> and here
 17            ELSE
 18               a.results
 19         END AS results
 20    FROM my_table a CROSS JOIN cnt b;

RESULTS
---------------------------------------------------
PQ count = 1

SQL>

【讨论】:

【参考方案2】:

您不能在创建别名的子查询中引用别名;您需要嵌套子查询(或使用子查询因式分解子句;也称为 CTE 或 WITH 子句)并在外部引用它:

SELECT CASE
       WHEN results LIKE '%PQ - Duplicate%'
       AND  pq_count >= 1 
       THEN 'PQ count = '|| pq_count
       ELSE results
       END AS RESULTS
FROM   (
  SELECT results,
         ( SELECT COUNT(*)
           FROM   MY_TABLE
           WHERE  ID = '998877'
           AND    FINAL_RESULTS='FL_57'
         ) AS pq_count
  FROM   your_table
);

【讨论】:

以上是关于子查询作为 CASE WHEN 条件的主要内容,如果未能解决你的问题,请参考以下文章

使用 CASE 作为 dblink 的一部分来获取数据

TSQL:SELECT CASE WHEN THEN 子查询:错误:子查询返回超过 1 个值

Oracle SQL:对 CASE WHEN 重复使用子查询,而无需重复子查询

从 CASE WHEN 语句中取出相关子查询

关于Hive中case when不准使用子查询的解决方法

hibernate hql case when 子查询报java.lang.NullPointerException错误