SQL Server:TOP以及Distinct

时间:2016-02-25 08:32:06

标签: sql sql-server sql-server-2008 distinct

我有两张表ProductsPurchaseDetails

Products表的架构是

ProductId  (primary key)
ProductName
CategoryId
Price
QuantityAvailable

PurchaseDetails表的架构是

PurchaseId
EmailId
ProductId
QuantityPurchased
DateOfPurchase

这个问题要求我找出大量购买的TOP 3产品。

我写了这个SQL查询:

Select TOP 3 
    Distinct(ProductName), Price, QuantityPurchased
from 
    Product, PurchaseDetails
where 
    Product.ProductId = PurchaseDetails.ProductId
order by 
    QuantityPurchased DESC

但是上面的查询会抛出错误。我不明白为什么上面的查询会产生错误?

2 个答案:

答案 0 :(得分:1)

以下查询将为您提供大量购买的前3个产品

Select TOP 3 ProductName,sum(Price) as [price],sum(QuantityPurchased) as QuantityPurchased
    from Product , PurchaseDetails
    where Product.ProductId=PurchaseDetails.ProductId
    group by ProductName
    order by QuantityPurchased DESC

答案 1 :(得分:0)

Select TOP 3 ProductName,sum(Price) as [price],sum(QuantityPurchased) as QuantityPurchased
    from Product , PurchaseDetails
    where Product.ProductId=PurchaseDetails.ProductId
    group by ProductName
    order by QuantityPurchased DESC