2012-01-17 19 views
0

我想查詢我的數據庫中查找該產品在十月比無論是11月或12銷售的更少。SQL - 比較和分組數據在多行

我認爲類似下面會做,但我有一種感覺,子查詢將返回mininimum量爲整個數據庫而不是具體的產品。

必須有這樣使用GROUP BY的一些方法,但我不明白。

SELECT Category, Product 
    FROM Sales 
WHERE SaleQuantity < (SELECT MIN(SaleQuantity) 
         FROM Sales 
         WHERE MonthNumber > 10) 
    AND MonthNumber = 10 

數據是這樣的:

Category Product  MonthNumber SaleQuantity 
---------- ----------- ------------- ----------- 
11   14   10   210 
11   14   11   200 
11   14   12   390 
15   12   10   55 
15   12   11   24 
17   12   12   129 
19   10   10   12 

感謝。

+0

這是SQL Server嗎?您是否考慮過產品,月份和分鐘(銷售)的CTE,然後加入? – 2012-01-17 11:12:09

+0

我只是想有可能是使用標準的SQL – BrightonDev 2012-01-17 11:16:36

+0

這是偏愛的事,但我與你在你的問題給出一個查詢的經驗是,你得到一個簡單,乾淨的實施,如果您使用的是得到這個數據的簡單方法CTE。 – 2012-01-17 13:13:06

回答

0


嘗試這樣的事情

SELECT Category, 
     Product, 
     SUM(s.SaleQuantity) AS saleOcotber, 
     SUM(ISNULL(son.SaleQuantity, 0)) AS saleNovember, 
     SUM(ISNULL(sod.SaleQuantity, 0)) AS saleDecember 
FROM Sales s 
    LEFT OUTER JOIN Sales son ON son.Category = s.Category 
    AND son.Product = s.Product 
    AND son.MonthNumber = 11 
    LEFT OUTER JOIN Sales sod ON sod.Category = s.Category 
    AND sod.Product = s.Product 
    AND sod.MonthNumber = 11 
WHERE s.MonthNumber = 10 
GROUP BY Category,Product 
WHERE SUM(s.SaleQuantity) < SUM(ISNULL(son.SaleQuantity, 0)) 
    OR SUM(s.SaleQuantity) < SUM(ISNULL(sod.SaleQuantity, 0)) 

我沒有測試過這個選擇,但我認爲如果有什麼不清楚 請詢問

最好的問候, 約爾丹

它會做的工作

PS。我相信你正在使用MSSQL的一些版本,如果不嘗試自己重寫它使用的是

0

你的表似乎已經按類別,產品和MonthNumber總結,對SalesQuantity INT SQL。如果是這樣,請試試這個:

select distinct Category, Product 
from Sales s11_12 
where MonthNumber in (11,12) and 
     not exists (select null 
        from Sales s10 
        where s10.Category = s11_12.Category and 
         s10.Product = s11_12.Product and 
         s10.SalesQuantity >= s11_12.SalesQuantity)