Sql组工作不正常

时间:2012-11-02 02:48:15

标签: sql sql-server tsql group-by

这是我的查询

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

如果我在查询中包含customername,则groupby无法正常工作。

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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

答案 2 :(得分: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子句,仍然可以获得表中所有记录的总和(输出中只有一行)。您只能按每个客户名获取记录总和,这是您的第二个查询应该执行的操作。因此,如果第二个查询不是您想要的,那么您就会遇到问题,因为您想要的内容在逻辑上可能与您拥有的数据无关