SQL Server:请确认我的查询是否提供正确的结果

时间:2019-01-02 03:41:57

标签: sql-server

我想显示哪些订单包含两个以上的产品?

显示订单号,订单值和该订单包含的产品数量。

仅供参考,我增加了2列,因为结果看起来会更好。

WITH RESULTS AS
(
    SELECT 
        *,
        COUNT(O2.SalesOrderID) OVER (PARTITION BY O2.SalesOrderID) AS COUNTS 
    FROM 
        AdventureWorks2014.Sales.SalesOrderDetail AS O2
    --  WHERE COUNTS > 1
    --  ORDER BY SalesOrderID ASC
)
SELECT 
    O.SalesOrderID,
    p.Name, P.ProductID, R.COUNTS as [Products Amount],
    R.LineTotal, R.OrderQty
FROM 
    RESULTS AS R
INNER JOIN 
    AdventureWorks2014.Sales.SalesOrderDetail AS O ON R.SalesOrderID = O.SalesOrderID
RIGHT JOIN 
    AdventureWorks2014.Production.Product as P ON P.ProductID = R.ProductID
WHERE
    R.COUNTS > 1
ORDER BY 
    O.SalesOrderID ASC

CLICK HERE TO SEE THE NEW IMAGE PLEASE

1 个答案:

答案 0 :(得分:0)

我做对了,我将联接移到了包含计数的RESULTS查询中,然后在COUNTS上放置了一个where子句并完成了工作

    WITH RESULTS AS
(
    SELECT O2.SalesOrderID
        ,O2.ProductID
        ,P.Name AS [Product Name]
        ,O2.UnitPrice
        ,O2.OrderQty
        ,O2.LineTotal
        ,COUNT(O2.SalesOrderID)OVER(PARTITION BY O2.SalesOrderID)  AS COUNTS 
    FROM AdventureWorks2014.Sales.SalesOrderDetail AS O2
    INNER JOIN AdventureWorks2014.Sales.SalesOrderHeader AS H ON O2.SalesOrderID = H.SalesOrderID
    INNER JOIN AdventureWorks2014.Production.Product as P ON P.ProductID = O2.ProductID
)

SELECT R.SalesOrderID
    ,R.[Product Name]
    ,R.ProductID
    ,R.COUNTS AS [Products Amount Per Order]
    ,R.OrderQty
    ,R.UnitPrice
    ,R.LineTotal AS [Total Payment Per Order]

FROM RESULTS AS R
WHERE R.COUNTS > 1
ORDER BY SalesOrderID ASC