简体   繁体   中英

Merging data SQL Query

I have a query request where I have to show one customer activity for each web-site but it has to be only one row each, instead of one customer showing multiple times for each activity. Following is the query I tried but brings lot more rows. please help me as how I can avoid duplicates and show only one customer by each row for each activity.

SELECT i.customer_id, i.SEGMENT  AS Pistachio_segment,
    (CASE when S.SUBSCRIPTION_TYPE = '5' then 'Y' else  'N' end ) PB_SUBS
    (CASE WHEN S.SUBSCRIPTION_TYPE ='12' THEN 'Y' ELSE 'N' END) Daily_test,
    (CASE when S.SUBSCRIPTION_TYPE ='8' then 'Y' else 'N' end) COOK_4_2
FROM IDEN_WITH_MAIL_ID i  JOIN CUSTOMER_SUBSCRIPTION_FCT S
ON I.IDENTITY_ID = S.IDENTITY_ID and I.CUSTOMER_ID = S.CUSTOMER_ID
WHERE s.site_code ='PB' and s.subscription_end_date is null

Sounds like you need to group by customer_id and perform aggregations for the other columns you are selecting. For example:

sum(case when s.subscription_type = '5' then 1 else 0 end) as pb_subs_count

You could try one of two things:

  1. Use a GROUP BY statement to combine all records with the same id, eg,

     ... WHERE s.site_code ='PB' and s.subscription_end_date is null GROUP BY i.customer_id
  2. Use the DISTINCT command in your SELECT, eg,

     SELECT DISTINCT i.customer_id, i.SEGMENT, ...

you could use a aggregation (SUM) on customer_id, but what do you expect to happen on the other fields? for example, if you have SUBSCRIPTION_TYPE 5 and 13 for the same customer (2 rows), which value do you want?

Perhaps you are looking for something like this:

SELECT i.customer_id, i.SEGMENT  AS Pistachio_segment,
    (CASE when S.SUBSCRIPTION_TYPE = '5' then 'Y' else  'N' end ) PB_SUBS
    (CASE WHEN S.SUBSCRIPTION_TYPE ='12' THEN 'Y' ELSE 'N' END) Daily_test,
    (CASE when S.SUBSCRIPTION_TYPE ='8' then 'Y' else 'N' end) COOK_4_2
FROM IDEN_WITH_MAIL_ID i  JOIN CUSTOMER_SUBSCRIPTION_FCT S
ON I.IDENTITY_ID = S.IDENTITY_ID and I.CUSTOMER_ID = S.CUSTOMER_ID
WHERE s.site_code ='PB' and s.subscription_end_date is null

I can't be sure, though, without knowing more about the tables involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM