sql - 查询以从一行中的同一列获取计算值
问题描述
编辑:输出也需要最大日期值,以防“dt”对不同的“dis_code”有不同的值。我在批准的答案中添加了 max(dt) ,但它并没有解决问题。
我的表如下所示:
Cust_id Trtmnt_cd dt dis_code
A A123 2019-01-15 SENT
A A123 2019-01-16 OPEN
A A123 2019-01-20 CLICK
我的代码:
select a.cust_id,a.trtmnt_cd,max(A.offr_proposed),max(B.cust_response)
FROM
(SELECT a.cust_id,a.trtmnt_cd,
case when trim(a.dis_code) in ('SENT') then 1 else 0 end as offr_proposed
FROM tbl1 a
group by cust_id,a.trtmnt_cd,a.dis_code) A
inner join
(SELECT b.cust_id,b.trtmnt_cd,
case when trim(b.dis_code) in ('OPEN','CLICK') then 1 else 0 end as cust_response
FROM tbl1 b
group by b.cust_id,b.trtmnt_cd,b.disp_code) B
On (A.cust_id = B.cust_id and A.trtmnt_cd = B.trtmnt_cd)
group by A.cust_id,A.trtmnt_cd,A.offr_proposed,B.cust_response
上述查询的输出:
Cust_Id trtmnt_cd offr_proposed cust_response
A A123 1 0
A A123 1 1
Desired Output:
Cust_Id trtmnt_cd dt offr_proposed cust_response
A A123 2019-01-20 1 1
基本上,我想要每个客户的唯一一行数据,它告诉我是否发送了报价(1 或 0)以及客户对该报价的响应(1 或 0)。当前数据表对于每个报价事件都有多行,即(1 行用于发送,另一行用于打开等)。
请指导我更正我的代码。
解决方案
使用条件聚合。
在 MySQL 中:
select
cust_id
trtmnt_cd,
max(dis_code = 'SENT') offr_proposed,
max(dis_code = 'CLICK') offr_response
from tbl1
group by cust_id, trtmnt_cd
在 SQL Server 中:
select
cust_id
trtmnt_cd,
max(case when dis_code = 'SENT' then 1 else 0 end) offr_proposed,
max(case when dis_code = 'CLICK' then 1 else 0 end) offr_response
from tbl1
group by cust_id, trtmnt_cd
您可以使用以下where
子句优化查询(如果报价没有上述两个事件,它将不会出现在结果集中):
where dis_code in ('SENT', 'CLICK')
推荐阅读
- discord.js - 我希望能够在创建时覆盖频道的权限
- mysql - 从 Web 服务器 API 并行调用时,AWS RDS 上的休眠 MySQL 连接数快速增加
- git - 在拉取请求和合并期间添加新文件
- react-native - 当触摸点在多个可触摸元素之间移动时,如何跟踪当前触摸的元素?
- python - 通过转置和设置其他列的值重新排序数据帧(熊猫)
- json - 如何解决json加载问题?
- javascript - blob 无法识别字体文件类型
- css - CSS Bootstrap Grid - 包装 Div 不是从其上方 Div 的底部开始
- python - Tensorflow - 在生产中尽可能高效地执行模型
- applescript - 运行 Apple 脚本时自动化失败