SQL Complex Select - 麻烦形成查询

时间:2010-04-29 05:09:48

标签: sql-server tsql aggregate

我有三个表,客户,销售和产品。

Sales将CustomerID与ProductID链接,并具有SalesPrice。

select Products.Category, AVG(SalePrice) from Sales 
inner join Products on Products.ProductID = Sales.ProductID
group by Products.Category

这让我可以按类别查看所有销售的平均价格。但是,我只想在数据库中包含超过3个或更多销售记录的客户。

我不确定最好的方式或任何方式来解决这个问题。想法?

4 个答案:

答案 0 :(得分:4)

您没有在任何地方提到客户数据,所以我认为它在Sales表

您需要首先将销售表过滤并限制为具有3个销售额的客户,然后加入以获取产品类别并获得不同类别的平均值

select
    Products.Category, AVG(SalePrice)
from
    (SELECT ProductID, SalePrice FROM Sales GROUP BY CustomerID HAVING COUNT(*) > 3) S
    inner join
    Products on Products.ProductID = S.ProductID
group by
    Products.Category

答案 1 :(得分:0)

我会尝试以下方法:

select Products.Category, AVG(SalePrice) from Sales s
inner join Products on Products.ProductID = s.ProductID
where 
(Select Count(*) From Sales Where CustomerID = s.CustomerID) > 3
group by Products.Category

答案 2 :(得分:0)

我使用select创建一个“大客户ID”的伪表,然后将其加入您的查询以限制结果:

SELECT Products.Category, AVG(SalePrice) FROM Sales
  INNER JOIN Products ON Products.ProductID = Sales.ProductID
  INNER JOIN (
    SELECT CustomerID FROM Sales WHERE COUNT(CustomerID) >= 3 GROUP BY CustomerID
  ) BigCustomer ON Sales.CustomerID = BigCustomer.CustomerID
  GROUP BY Products.Category

虽然太懒了测试它,所以让我知道它是否有效; o)

答案 3 :(得分:0)

另一种方式

;WITH FilteredSales AS
(
SELECT Products.Category, Sales.SalesPrice, COUNT(Sales.CustomerId) OVER(PARTITION BY Sales.CustomerId) AS SaleCount
FROM Sales
INNER JOIN Products ON Products.ProductID = Sales.ProductID
)
select Category, AVG(SalePrice)
from FilteredSales
WHERE SaleCount > 3
group by Category