2012-10-23 73 views
1

我有一個查詢,將是這樣的返回所有的銷售價值和銷售價值的總和爲每個產品

SELECT 
    ProductID, 
    ProductSales, 
    ProductLocationName 
FROM 
    ProductLocation 
WHERE 
    [email protected] 

所以我的樣本結果可能是這樣的

ProductID ProductSales ProductLocationName 
1   $2    Boston 
1   $2    Chicago 
2   $8    Boston 

有一些productID/ProductSales如果ProductLocationName不同,但我需要返回的組合是重複的如下組合:

我需要返回我在上面返回的內容樣本結果,但除此之外,我需要總結所有ProductSales值,除了重複ProductID/ProductSales組合。從上面

例子:

ProductID 1 + ProductID 2 
$2 + $8 = $10 

請注意,我沒有加$兩次2,因爲這prodID/Sales值在結果重複,但我仍然需要返回到上面,因爲我要顯示所有3的3行在我的轉發器中的行。

希望我是清楚的,除了ProductID & ProductLocation(也有將包含在我的查詢等欄目),我需要

  1. ProductSales(如顯示在以上SampleResults)每個ProductID。我知道SUM(ProductSales)會讓我這個。

  2. ProductSalesSUM所有獨特ProductID值($ 2 + $ 8 = $ 10)

我想如果可能這樣做所有這一切都在相同的存儲過程。

我最關心的是如何獲得2點,這意味着SUM所有ProductSales值的,在我的例子$ 2 + $ 8

請讓我知道如果你需要更多的信息,這是我在這裏的第一篇文章。

回答

0

爲了正確地做到這一點,你需要一個子查詢計算:

SELECT ProductID, ProductSales, ProductLocationName, t.SumProductSales 
FROM ProductLocation pl cross join 
    (select sum(ProductSales) as SumProductSales 
     from (select productId, max(ProductSales) as ProductSales 
      from ProductionLocation pl 
      group by productId 
      ) p 
    ) t 
WHERE [email protected] 

你需要注意的是有ProductSales相同的值不同的產品。

+0

謝謝,我該如何做同樣的平均(AVG)?或者應該是另一個帖子? – user1768680

+0

只需將Sum(ProductSales)替換爲SumProductSales'作爲'Avg(ProductSales)作爲AvgProductSales'並在查詢中使用該字段。如果你喜歡,你可以實際包含兩者。 –