SQL - 比较和分组多行数据

时间:2012-01-17 11:06:40

标签: sql

我正在尝试查询我的数据库,以查找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

感谢。

2 个答案:

答案 0 :(得分: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,如果没有尝试自己重写它正在使用的SQL

答案 1 :(得分:0)

对于SalesQuantity,您的表格似乎已按类别,产品和月份编号进行汇总。如果是这样,试试这个:

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)