我想计算客户曾经拥有的所有订单的订单明细行总数。
这是我的查询
SELECT SUM(
(SELECT count(*)
FROM dbo.Order_Details
WHERE dbo.Order_Details.OrderID = dbo.Orders.OrderID))
FROM dbo.Orders
WHERE dbo.Orders.CustomerID = "123"
SQL Server给我一个错误“无法对包含聚合或子查询的表达式执行聚合函数。”
对此有任何帮助将不胜感激。
答案 0 :(得分:3)
SELECT COUNT(*)
FROM Orders
INNER JOIN Order_Details ON Orders.OrderID = Order_Details.OrderID
WHERE Orders.CustomerID = "123"
答案 1 :(得分:0)
你不需要sum(),因为count(*)已经为你提供了总数。
SELECT (SELECT count(*)
FROM dbo.Order_Details
WHERE dbo.Order_Details.OrderID = dbo.Orders.OrderID)
FROM dbo.Orders
WHERE dbo.Orders.CustomerID = "123"
答案 2 :(得分:0)
不应该只是:
SELECT count(*) FROM dbo.Order_Details, dbo.Orders
WHERE dbo.Order_Details.OrderID = dbo.Orders.OrderID
AND dbo.Orders.CustomerID = "123"
答案 3 :(得分:0)
Count(*)正在为你做总结。只需从表达式中删除SUM聚合。
答案 4 :(得分:0)
我认为以下内容应该做你想做的事情:
select count(1) from dbo.order_details d
join dbo.orders o on d.OrderId=o.OrderId
where dbo.orders.CustomerID="123"
答案 5 :(得分:0)
以下假设您在Order_Details表中有一个名为OrderDetailID的列。如果没有,只需替换订单明细记录的唯一标识符。
SELECT COUNT(DISTINCT OD.OrderDetailID)
FROM Orders O
LEFT JOIN Order_Details OD on (OD.OrderId = O.OrderId)
WHERE O.CustomerID = "123"