时间:2015-12-09 10:12:20

标签: sql-server window-functions

我正在学习sql server中的窗口函数。我正在使用AdventrueWorks2012数据库进行练习。我想计算商店中每件商品的总销售量和购买量。

经典解决方案可以像

    SELECT ProductID,
       Quantity,
       (SELECT Count(*)
        FROM   AdventureWorks.Purchasing.PurchaseOrderDetail
        WHERE  PurchaseOrderDetail.ProductID = p.ProductID) TotalPurchases,
       (SELECT Count(*)
        FROM   AdventureWorks.Sales.SalesOrderDetail
        WHERE  SalesOrderDetail.ProductID = p.ProductID)    TotalSales
FROM   (SELECT DISTINCT ProductID,
                        Quantity
        FROM   AdventureWorks.Production.ProductInventory) p

尝试转换为窗口函数会给我错误的结果:

    SELECT DISTINCT d.ProductID,
                Quantity,
                Count(d.ProductID)
                  OVER(
                    PARTITION BY d.ProductID)  TotalPurchases,
                Count(d2.ProductID)
                  OVER(
                    PARTITION BY d2.ProductID) TotalSales
FROM   (SELECT DISTINCT ProductID,
                        Quantity
        FROM   AdventureWorks.Production.ProductInventory) p
       INNER JOIN AdventureWorks.Purchasing.PurchaseOrderDetail d
               ON p.ProductID = d.ProductID
       INNER JOIN AdventureWorks.Sales.SalesOrderDetail d2
               ON p.ProductID = d2.ProductID
ORDER  BY d.ProductID

为什么这是错的?我该如何纠正?

1 个答案:

答案 0 :(得分:1)

您应该将INNER JOIN更改为LEFT JOIN

因为当您加入内部时,结果将会遗漏来自ProductInventory表没有PurchaseOrderDetailSalesOrderDetail的productid。