tags:

views:

63

answers:

2

hi guys

I am trying to get the total count and total sum per salesperson but its not working in my WITH query

Currently I have:

 WITH CALC1 AS (
   SELECT B.OTSMAN AS SALESMAN, COUNT(B.ONINUM) AS COUNT, SUM(B.OVSVAL) AS SVAL 
   FROM @[email protected] 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

THE RESULT IS:

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

How do i change my query so I only get one record with the total count and value per salesperson?

AM  1   13,011.84
+1  A: 

Change the GROUP BY to

GROUP BY B.OTSMAN

Something like

;WITH CALC1 AS (
        SELECT  B.OTSMAN AS SALESMAN, 
                COUNT(B.ONINUM) AS COUNT, 
                SUM(B.OVSVAL) AS SVAL 
        FROM    @[email protected] 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 
astander
A: 

You need to change your group by like this:

with calc1 as 
(select b.otsman as salesman, 
        count(distinct b.oninum) as count, 
        sum(b.ovsval) as sval 
   from @[email protected] 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

Update: Updated to get distinct orders count per salesman

Dougman
thanks for the quick responses!i want my result to show:AM 7 13,011.84i need to show that there are 7 records for that salesperson and not the actual count of 185...how do i do that?do i need another WITH?
Odette
@Odette: Which field defines a unique record for that salesperson? You would update the count query to be count(distinct <field that is unique to inidicate inidividual sale for salesperson>).
Dougman
that worked a treat!thanks Dougman
Odette