Sql 使用子查询时的大小写求和
我需要找到特定细分市场的客户数量 以及拥有有效邮件或手机以及特定细分市场特定品牌的客户数量 表格如下:Sql 使用子查询时的大小写求和,sql,sql-server,tsql,Sql,Sql Server,Tsql,我需要找到特定细分市场的客户数量 以及拥有有效邮件或手机以及特定细分市场特定品牌的客户数量 表格如下: 拥有客户+品牌的“来源” “客户”包含客户、电子邮件、手机 包含电子邮件的“部分”(参考客户) 我有一些限制:我构建了矩阵查询,所以在结构时需要使用案例 这就是我写的——不好 SELECT count(*) as CountCustomers, sum(case when Customerid in (select distinct customerid from
- 拥有客户+品牌的“来源”
- “客户”包含客户、电子邮件、手机
- 包含电子邮件的“部分”(参考客户)
案例
这就是我写的——不好
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)
我的问题是当我不知道如何正确地写的时候
这就是错误:
“无法对包含聚合或子查询的表达式执行聚合函数”
希望你能理解我的问题并能帮助我
非常感谢您花费的时间和精力。也许您可以将子查询移动到左联接,这样聚合子句就不会出现问题
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)
这是伪代码,请检查正确的语法将该子查询移动到外部应用/左连接
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
这两种区别看起来都很难看,但也许扫描比循环更适合这里。我不太喜欢通过电子邮件加入。样本数据和期望的结果会很有帮助。