我正在尝试查询我的数据库,找出哪些产品在10月份的销量低于11月份或12月份。
我想像下面这样的东西就可以了,但我有一种感觉,子查询将返回整个数据库的最小数量,而不是特定产品的最小数量。
一定有一些方法可以使用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谢谢。
发布于 2012-01-17 19:16:28
试试这样的东西
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 ) )我没有测试这个选择,但我认为它可以做的工作,如果有什么不清楚,请询问
致以最好的问候,Iordan
PS。我假设您使用的是某个版本的MSSQL,如果不是尝试在您正在使用的SQL中自己重写它
发布于 2012-01-17 19:21:00
对于SalesQuantity,您的表已经按类别、产品和MonthNumber进行了汇总。如果是这样的话,试试这个:
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)https://stackoverflow.com/questions/8893548
复制相似问题