简体   繁体   English

合并数据 SQL 查询

[英]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.听起来您需要按 customer_id 分组并为您选择的其他列执行聚合。 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,使用 GROUP BY 语句组合具有相同 ID 的所有记录,例如,

     ... 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 命令,例如,

     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?您可以在 customer_id 上使用聚合 (SUM),但您希望在其他字段上发生什么? for example, if you have SUBSCRIPTION_TYPE 5 and 13 for the same customer (2 rows), which value do you want?例如,如果同一客户(2 行)有 SUBSCRIPTION_TYPE 5 和 13,您想要哪个值?

Perhaps you are looking for something like this:也许您正在寻找这样的东西:

SELECT i.customer_id, i.SEGMENT  AS Pistachio_segment,
    MAX(CASE when S.SUBSCRIPTION_TYPE = '5' then 'Y' else  'N' end ) PB_SUBS
    MAX(CASE WHEN S.SUBSCRIPTION_TYPE ='12' THEN 'Y' ELSE 'N' END) Daily_test,
    MAX(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
GROUP BY i.customer_id, i.SEGMENT

I can't be sure, though, without knowing more about the tables involved.但是,如果不了解更多有关所涉及表格的信息,我无法确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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