sum具有多个值的聚合函数

时间:2015-03-22 16:37:05

标签: sql sql-server sql-server-2008 tsql

我的整个代码在这里:

    select top (@selectCount) w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.userId,  q.bidedItem, SUM(q.bidCount) as sumOfBids, sum(w.codesLeft + q.bidCount) as 'allCode'
from geopl_kubetiAuct.secondWeekBids as q 
join geopl_kubetiAuct.Users w on q.userId = w.Id
where q.bidedItem = @Prize 
group by w.firstName, w.lastName, w.fbId, w.idNumber, w.address, w.phoneNumber, q.bidedItem, q.userId
order by sumOfBids desc

我有

的问题
sum(w.codesLeft + q.bidCount) as 'allCode'

如果q.bidCount大于1,则会迭代此w.codesLeft和q.bidCount,因为那里有很多出价。例如,如果有2个投标结果将

  

2 + 5 + 2 + 10   (codesLeft为2,第一次出价为5,第二次为10)

我该如何改进?

AllCode必须返回(2 + 5 + 10)

2 个答案:

答案 0 :(得分:1)

如果我理解正确,问题是在w.codesLeft之前的每一行都会显示group by。它在这个中间数据集上得到一个单独的值,所以当你总结它时,你会得到错误的值。

解决方案是使用max(w.codesLeft)而不仅仅是codesLeft

select top (@selectCount) w.firstName, w.lastName, w.fbId, w.idNumber,
        w.address, w.phoneNumber, q.userId, q.bidedItem,
        SUM(q.bidCount) as sumOfBids,
        (max(w.codesLeft) + sum(q.bidCount)) as allCode
from geopl_kubetiAuct.secondWeekBids q join
     geopl_kubetiAuct.Users w
     on q.userId = w.Id
where q.bidedItem = @Prize 
group by w.firstName, w.lastName, w.fbId, w.idNumber,
         w.address, w.phoneNumber, q.bidedItem, q.userId
order by sumOfBids desc;

但是,这假设您的查询最初是sum(w.codesLeft + q.bidCount) - 如果没有sum()您仍会收到错误。

答案 1 :(得分:0)

你必须这样: (sum(w.codesLeft) + sum(q.bidCount)) as 'allCode'

因为在sum运算符中,您只能写一列。 有关Sum运算符的详细信息,请转到此msdn link