2010-04-23 84 views
3

我試圖讓每個銷售人員的總數和總金額,但它不是我的工作與查詢如何使用sum和count函數

目前我有:

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 (@[email protected]) 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 
+1

我不相信您的查詢有效。你把「ORDER BY B.OTSMAN ASC」放在cte中,我猜sql server會拋出一個錯誤。 – zsong 2010-04-23 03:14:16

回答

0

您需要通過這樣的改變你的組:

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 (@[email protected]) 
    and b.icmatx <> '705' 
    and b.ocsgrp not like 'S/%' 
group by b.otsman 
) 
select salesman, 
     count, 
     sval 
    from calc1 
order by salesman 

更新:更新爲獲得每個銷售員的不同訂單數量

+0

感謝您的快速回復! 我想我的結果顯示: 上午7 13,011.84 我需要表明,有7條記錄爲銷售人員,而不是185的實際計數... 我怎麼做,我需要另一個WITH? – Odette 2010-04-23 03:26:39

+0

@Odette:哪個字段爲該銷售人員定義了唯一記錄?您將更新計數查詢以進行計數(獨特<爲銷售人員推銷個人銷售所特有的字段>)。 – 2010-04-23 05:08:16

+0

工作的一種享受! 謝謝道格曼 – Odette 2010-04-23 05:16:31

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 @[email protected] AS B 
     WHERE B.OCSGRP <> 'INT' 
     AND  B.OCSGRP <> 'INX' 
     AND  B.OCPSBR IN (@[email protected]) 
     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