2010-02-16 47 views
4

我有這個表:計數或不計數,這是個問題

Strawberries 2 
Strawberries 3 
Strawberries 4 
Chocolate 3 
Chocolate 4 
Chocolate 5 
Chocolate 6 
Apples 3 
Apples 4 
Apples 5 
Apples 6 

我的想法是讓項目的數量,以及總的每一點的項目,就像這樣:

Item   Number  Total 
Strawberries 2    9 
Strawberries 3    9 
Strawberries 4    9 
Chocolate 3    18 
Chocolate 4    18 
Chocolate 5    18 
Chocolate 6    18 
Apples  3    18 
Apples  4    18 
Apples  5    18 
Apples  6    18 

所以我做:

SELECT  TOP (100) PERCENT item, number, COUNT(number) AS total FROM products 
GROUP BY item, number 
ORDER BY item 

,但我得到的數字都是錯誤的:

Item   Number  Total 
Strawberries 2    6 
Strawberries 3    21 
Strawberries 4    17 
Chocolate 3    1 
Chocolate 4    8 
Chocolate 5    34 
Chocolate 6    1 
Apples  3    1 
Apples  4    10 
Apples  5    32 
Apples  6    1 

我在做什麼錯?

回答

6
SELECT item, number, SUM(number) OVER (PARTITION BY item) 
FROM products 
ORDER BY 
     item, number 
+0

我想你是指'SUM(數字)'而不是'COUNT(*)'。 – Codesleuth 2010-02-16 11:47:28

+0

@Codesleuth:哦,你說得對,我確定。 – Quassnoi 2010-02-16 11:48:32