首页 > 解决方案 > 在 case 语句中使用相关子查询

问题描述

我正在尝试在我的 sql 代码中使用相关子查询,但我无法理解我做错了什么。关于代码的简要描述以及我正在尝试做的事情:

该代码由一个大查询(ALIASED AS A)组成,其结果集看起来像一个客户 ID 列表、报价 ID 和响应状态名称(“SOLD”、“SELLING”、“IRRELEVANT”、“NO ANSWER”等)每个客户对每个报价。结果集中的客户 ID 和响应是不唯一的,因为可以向每个客户提供多个报价,并且客户可以对不同的报价有不同的响应。

目标是生成不同客户 ID 的列表,并用 0 或 1 标志标记每个 ID:如果 ID 有至少一个状态名称为“已售”或“已售”的报价,则标志应为 1,否则为 0。每个客户都有一系列不同的响应,我想要做的是检查每个客户 ID 的数组中是否出现“SOLD”或“SELLING”,在 case 语句中使用相关子查询并为名为这次是 A 和 A1:

select distinct
A.customer_ID,

case when 'SOLD' in  (select distinct A1.response from A  as A1
                        where A.customer_ID = A1.customer_ID) OR

          'SELLING' in (select distinct A1.response from A  as A1
                        where A.customer_ID = A1.customer_ID) 

           then 1 else 0 end as FLAG
FROM
(select …) A

我得到的是一个错误警报,说没有像 A 或 A1 这样的对象。在此先感谢您的帮助!

标签: sql

解决方案


您可以exists使用cte

with cte as (
     <query here> 
)
select c.*,
       (case when exists (select 1 
                          from cte c1 
                          where c1.customer_ID = c.customer_ID and 
                                c1.response in ('sold', 'selling')
                         )
             then 1 else 0 
        end) as flag
from cte c;

您还可以进行聚合:

select customer_id, 
       max(case when a.response in ('sold', 'selling') then 1 else 0 end) as flag
from < query here > a;
group by customer_id;

推荐阅读