如何使用sum和count函数

时间:2010-04-23 03:08:33

标签: sql debugging

我正在尝试获取每个销售人员的总计数和总金额,但它不能在我的WITH查询中使用

目前我有:

 WITH CALC1 AS (
   SELECT B.OTSMAN AS SALESMAN, COUNT(B.ONINUM) AS COUNT, SUM(B.OVSVAL) AS SVAL 
   FROM @LIB@.DGLOESUMD AS B 
   WHERE B.OCSGRP <> 'INT' AND 
         B.OCSGRP <> 'INX' AND 
         B.OCPSBR IN (@OCPSBR@) AND 
         B.ICMATX <> '705' AND 
         B.OCSGRP NOT LIKE 'S/%' 
  GROUP BY B.OTSMAN, B.ONINUM ORDER BY B.OTSMAN ASC
 )
 SELECT SALESMAN, COUNT,  SVAL FROM CALC1 ORDER BY SALESMAN

结果是:

AM  1   79.03
AM  40  1337.70
AM  48  4627.15
AM  42  2727.40
AM  1   111.79
AM  1   1110.00
AM  52  3018.77

如何更改查询,以便我只获得一条记录,其中包含每位销售人员的总数和值?

AM  1   13,011.84

2 个答案:

答案 0 :(得分:1)

GROUP BY更改为

GROUP BY B.OTSMAN

这样的东西
;WITH CALC1 AS (
        SELECT  B.OTSMAN AS SALESMAN, 
                COUNT(B.ONINUM) AS COUNT, 
                SUM(B.OVSVAL) AS SVAL 
        FROM    @LIB@.DGLOESUMD AS B 
        WHERE   B.OCSGRP <> 'INT' 
        AND     B.OCSGRP <> 'INX' 
        AND     B.OCPSBR IN (@OCPSBR@) 
        AND     B.ICMATX <> '705' 
        AND     B.OCSGRP NOT LIKE 'S/%' 
        GROUP BY    B.OTSMAN
        ORDER BY    B.OTSMAN ASC
) 

SELECT  

SALESMAN, 
COUNT,  
SVAL 

FROM CALC1 

ORDER BY SALESMAN 

答案 1 :(得分:0)

您需要像这样更改您的群组:

with calc1 as 
(select b.otsman as salesman, 
        count(distinct b.oninum) as count, 
        sum(b.ovsval) as sval 
   from @lib@.dgloesumd as b 
  where b.ocsgrp <> 'INT' 
    and b.ocsgrp <> 'INX' 
    and b.ocpsbr in (@ocpsbr@) 
    and b.icmatx <> '705' 
    and b.ocsgrp not like 'S/%' 
 group by b.otsman 
)
select salesman,
       count, 
       sval
  from calc1
order by salesman

更新:已更新,以便为每个销售员获取不同的订单数