与子查询时的总和

时间:2018-10-08 22:47:26

标签: sql sql-server tsql

我需要找到特定细分市场中的客户数量 以及拥有来自特定细分市场的有效邮件或手机以及特定品牌的客户数量。

表为:

  • 拥有客户和品牌的“来源”
  • 拥有客户,电子邮件,手机的“客户”
  • 保存电子邮件(引用客户)的“细分”

我有一些限制:我建立矩阵查询,所以我需要使用case when结构。

这就是我写的-不好

SELECT
  count(*) as CountCustomers,
  sum(case when Customerid in
         (select distinct customerid from source
            where brand like '%abc%')
          and (Cellphone not in ('0' ,'-1') or email not like '%@NoEmail.com') 
        then 1 else 0 end
  ) as EmailOrSms
from customer 
where email in(select distinct email from segment where p=1)

我的问题是我不知道如何正确编写它。

这是错误:

  

“无法对包含聚合或子查询的表达式执行聚合函数”

希望您能理解我的问题,并且可以帮助我 非常感谢您的时间和精力。

2 个答案:

答案 0 :(得分:1)

也许您可以将子查询移至左联接,所以聚合子句没有问题

select
count (*) as CountCustomers,
sum(case when source.customerid is null then 0 else 1 end) as EmailOrSms
from customer
left join source on source.customerid = customer.Customerid and brand like '%abc' 
    and (Cellphone not in ('0' ,'-1') or email not like '%@NoEmail.com') 
where email in(select distinct email from segment where p=1)

这是伪代码,请检查正确的语法

答案 1 :(得分:1)

将子查询移至外部应用/左连接

SELECT
  count(*) as CountCustomers,
  sum(case when s.customerid is not null
          and (Cellphone not in ('0' ,'-1') or email not like '%@NoEmail.com') 
        then 1 else 0 end
  ) as EmailOrSms
from customer c
left join (
   select distinct customerid 
   from source
   where brand like '%abc%'
) s on s.customerid = c.customerid
inner join (
   select distinct email 
   from segment where p=1
) g on g.email = c.email

两个区别看起来都很丑陋,但也许扫描比循环更合适。而且我不太喜欢通过电子邮件加入。