sql - 在 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 这样的对象。在此先感谢您的帮助!
解决方案
您可以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;
推荐阅读
- pandas - 如何使用 pandas(xlsxwriter)在 excel 中设置受保护(或锁定)单元格的列宽?
- javascript - 无法在单击按钮时捕获表中的单选按钮值
- php - 在 mail() 工作 PHP/Javascript 时显示“正在发送...”
- java - Apache Beam Text IO writer 没有将无限源写入文件
- node.js - 如何通过快速发布请求强制客户端重定向到登录页面?
- c# - XML 文档不添加新条目
- python - 使用 jupyter notebook 在 python 虚拟环境中安装包
- javascript - 如何在 NodeJS 中获取 __proto__?
- extract - 是否有工具或脚本可以将分阶段的 VCF 拆分为两个单独的单倍体 VCF,每个单倍体一个?(Linux)
- android - 如何在 Android 中从 FMOD 获取声音数据