1

这是我的查询

select  
 (sum(case when offer1_delivered is not null then 1 else null end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else null end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename

输出

PenetrationRate1    PenetrationRate2    TargetMkgListID 
1                   2                3

我需要在此查询中包含 customername 列

select  customername,
 (sum(case when offer1_delivered is not null then 1 else null end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else null end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename
group by customername

如果我在查询中包含客户名称,则 groupby 无法正常工作。

4

3 回答 3

4
SELECT  customername
,(ISNULL(SUM(CASE WHEN offer1_delivered is not null THEN 1 ELSE 0 END),0)) AS PenetrationRate1
,(ISNULL(SUM(CASE WHEN offer2_delivered is not null THEN 1 ELSE 0 END),0)) AS PenetrationRate2
,COUNT(TargetMkgListID) as TargetMkgListID from tablename
GROUP BY customername 
于 2012-11-02T03:20:19.687 回答
1
select  customername,
 (sum(case when offer1_delivered is not null then 1 else 0 end) ) as PenetrationRate1
,(sum(case when offer2_delivered is not null then 1 else 0 end)) as PenetrationRate2
,count(TargetMkgListID) as TargetMkgListID from tablename
group by customername
于 2012-11-02T02:50:53.470 回答
1

假设表中只有一个 customerName 值,请尝试

select Min(customername),
       sum(case when offer1_delivered is not null then 1 end) PenetrationRate1,
       sum(case when offer2_delivered is not null then 1 end) PenetrationRate2,
       count(TargetMkgListID) TargetMkgListID 
from tablename

如果表中有多个 customerName,那么您不能将 customerName 添加到 Select 子句中,并且仍然可以获取表中所有记录的总和(输出中只有一行)。您只能按每个客户名称获取记录的总和,这是您的第二个查询应该执行的操作。因此,如果第二个查询不是您想要的,那么您就会遇到问题,因为您想要的数据在逻辑上可能无法使用您拥有的数据

于 2012-11-02T02:52:49.010 回答