我是SQL的新手,并尝试在我的SQL语句中创建一个子查询,该子查询查找别名列中所有总计的总和。我对如何格式化子查询感到有点困惑,每次我尝试它都说我格式化不正确。
cmd.CommandText = "SELECT ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * Quantity AS total, SUM(SELECT(total)) AS finalTotal " +
"FROM Products, [Order Details] AS OD " +
"WHERE OD.ProductID = Products.ProductID AND orderID = @OrderID";
如果我尝试上面的代码,我会收到一条错误,说我在SELECT语句附近有不正确的语法。任何帮助表示赞赏!
答案 0 :(得分:1)
如果您需要获取所有行的总和,可以SUM
使用OVER
SELECT *,SUM(total)OVER() AS finalTotal
FROM
(
SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
FROM Products P
JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
WHERE OD.orderID = @OrderID
) q
答案 1 :(得分:0)
问题出在SUM(SELECT(total))
,你不能以这种方式调用select,你必须指定from
子句来创建一个子查询。
如果您需要获得所有行的总和(单价*数量),那么:
SELECT Sum (UnitPrice * Quantity) AS total FROM Products
JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
WHERE OD.orderID = @OrderID
如果你需要为记录集重复这一点,那么:
SELECT *,SUM(total)OVER() AS OverAllTotal
FROM
(
SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
FROM Products P
JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
WHERE OD.orderID = @OrderID
) subQuery