首页 > 解决方案 > 查询以从一行中的同一列获取计算值

问题描述

编辑:输出也需要最大日期值,以防“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 行用于发送,另一行用于打开等)。

请指导我更正我的代码。

标签: sqlsql-serverpivot

解决方案


使用条件聚合。

在 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')

推荐阅读