SQL query to get computed values from the same column in one row

vagautam :

EDIT: OUTPUT requires the maximum date value too in case 'dt' has different values for different 'dis_code'. I added max(dt) to the approved answer but it doesn't solve the problem.

My table looks as below:

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

My code:

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

Output of the above query:

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

Basically, I want one unique row of data for each customer which tells me if the offer was sent (1 or 0 ) and the cust response to that offer (1 or 0). The Current data table has multiple rows for each offer event i.e. (1 row for sent, another if opened etc).

Please guide me to correct my code.

GMB :

Use conditional aggregation.

In 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

In 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

You could possibly optimize the query with the following where clause (then if an offer has none of the two above events, it will not appear in the resultset):

where dis_code in ('SENT', 'CLICK')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193857&siteId=1