我需要知道查询中的问题在哪里,我该如何解决?
SQL查询:
SELECT
P.NameAr, P.NameEn,
Sum(p.OrderQty) AS SumQty ,
Sum(p.OrderQty * P.NewPrice) AS SumQtyPrice ,
ROW_NUMBER() OVER(ORDER BY D.ProductID ASC) AS Number,
'Soon' AS ColSoon
FROM OrderMasters M
INNER JOIN OrderDetails D ON D.OrderMasterID = M.OrderMasterID
INNER JOIN Products P ON P.ProductID = D.ProductID
INNER JOIN Categories C ON C.CategoryID = P.CategoryID
GROUP BY P.NameAr, P.NameEn
Order By D.OrderDetailsID
错误消息:
Msg 8120,Level 16,State 1,Line 7
Column' OrderDetails.ProductID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
当我删除包含@RowNumber
代码的行执行时没有问题,但我在查询中需要它。
答案 0 :(得分:3)
您不能按字段申请不属于分组的字段;
所以,你应该按照条款
更改你的订单SELECT
P.NameAr, P.NameEn,
Sum(p.OrderQty) AS SumQty ,
Sum(p.OrderQty * P.NewPrice) AS SumQtyPrice ,
ROW_NUMBER() OVER(ORDER BY P.NameAr ASC) AS Number,
'Soon' AS ColSoon
FROM OrderMasters M
INNER JOIN OrderDetails D ON D.OrderMasterID = M.OrderMasterID
INNER JOIN Products P ON P.ProductID = D.ProductID
INNER JOIN Categories C ON C.CategoryID = P.CategoryID
GROUP BY P.NameAr, P.NameEn
Order By P.NameAr
我将P.NameAr
作为订单字段提供示例。
答案 1 :(得分:1)
SELECT
P.NameAr, P.NameEn,
Sum(p.OrderQty) AS SumQty ,
Sum(p.OrderQty * P.NewPrice) AS SumQtyPrice ,
ROW_NUMBER() OVER(ORDER BY D.ProductID ASC) AS Number,
'Soon' AS ColSoon,
D.OrderDetailsID
FROM OrderMasters M
INNER JOIN OrderDetails D ON D.OrderMasterID = M.OrderMasterID
INNER JOIN Products P ON P.ProductID = D.ProductID
INNER JOIN Categories C ON C.CategoryID = P.CategoryID
GROUP BY P.NameAr, P.NameEn,D.ProductID,D.OrderDetailsID
Order By D.OrderDetailsID
我解决了这个问题所有提示
答案 2 :(得分:0)
GROUP BY也应包含D.PRODUCTID:
group by p.NameAr, p.NameEn, d.ProductID