SQL Server Sum Aggregate函数 - 过滤结果集?

时间:2014-05-28 04:13:19

标签: sql sql-server filter aggregate

我有一个非常通用的查询,它按ID分组并汇总卷并获取最大地址号。当我运行它时,我得到以下记录计数:

SELECT (case when m.participant_id=0 then 100000000 + m.member_id else m.participant_id      END) as PID, 
    max(m.address_no) as address_no, sum(e.volume) as P3M_Vol into dbo.tmp_MC_P3M_FuelsPromo_3      
  from dbo.MonthlyDataMart e 
  inner join dbo.v_sr_member m on e.member_id = m.member_id
  where e.member_type_cd = 'MC' 
    and e.year = 2014 and e.month between 2 and 4 
    and e.tran_code in ('PTSEARN','PREMIUM')
    and not exists (select 1 from dbo.v_DNC d where e.member_id = d.member_id)         
group by (case when m.participant_id=0 then 100000000 + m.member_id else m.participant_id END) 

我收到以下消息:

Warning: Null value is eliminated by an aggregate or other SET operation.

(16828 row(s) affected)

然后我删除了查询中的sum(e.volume)列(以下代码:)

SELECT (case when m.participant_id=0 then 100000000 + m.member_id else m.participant_id END) as PID, 
    max(m.address_no) as address_no into dbo.tmp_MC_P3M_FuelsPromo_2        
  from dbo.MonthlyDataMart e 
  inner join dbo.v_sr_member m on e.member_id = m.member_id
  where e.member_type_cd = 'MC' 
    and e.year = 2014 and e.month between 2 and 4 
    and e.tran_code in ('PTSEARN','PREMIUM')
    and not exists (select 1 from dbo.v_DNC d where e.member_id = d.member_id)         
group by (case when m.participant_id=0 then 100000000 + m.member_id else m.participant_id END) 

我获得了不同的行数!

Warning: Null value is eliminated by an aggregate or other SET operation.

(34023 row(s) affected)

知道为什么会这样吗?我只删除了聚合函数,行数不一样。我正在使用MS SQL 2000。

2 个答案:

答案 0 :(得分:0)

Max()和sum()函数正在消除此查询中的空值。 错误是针对这些函数中的列。 受影响的行是由于aggrigate函数在组内没有sum()。 祝你好运

答案 1 :(得分:0)

在您正在聚合的值中使用ISNULL。仔细查看查询中您想要的确切行为!

您的错误行不同的原因是您正在对潜在的NULLS进行分组,聚合和内部联接。根据记录被跳过的位置,您可以得到非常多变的结果。