tags:

views:

47

answers:

6

Hi,

I want to count the total number of order detail rows over all orders a customer has ever had.

This is my query

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 is giving me an error "Cannot perform an aggregate function on an expression containing an aggregate or a subquery."

Any help with this would be appreciated.

A: 

You don't need the sum() since the count(*) is already going to give you the total.

SELECT (SELECT count(*) 
    FROM dbo.Order_Details 
    WHERE dbo.Order_Details.OrderID = dbo.Orders.OrderID)
FROM dbo.Orders
WHERE dbo.Orders.CustomerID = "123"
Adam Ruth
A: 

Shouldn't it just be:

SELECT count(*) FROM dbo.Order_Details, dbo.Orders 
 WHERE dbo.Order_Details.OrderID = dbo.Orders.OrderID
 AND dbo.Orders.CustomerID = "123"
Jim Schubert
A: 

The Count(*) is doing the summation for you. Just remove the SUM aggregate from your expression.

Geodesic
A: 

I should think something like the following should do what you want:

select count(1) from dbo.order_details d
join dbo.orders o on d.OrderId=o.OrderId
where dbo.orders.CustomerID="123"
Daniel
+3  A: 
SELECT COUNT(*)
FROM Orders
    INNER JOIN Order_Details ON Orders.OrderID = Order_Details.OrderID
WHERE Orders.CustomerID = "123"
Miles
+1: This is exactly the same query as I posted, but with different syntax. (INNER JOIN vs WHERE clause). SQL Server apparently optimizes both of these to be relatively the same performance, as mentioned here: http://www.bennadel.com/blog/284-SQL-Optimization-And-ON-Clause-vs-WHERE-Clause.htmWhen I started using Oracle at my current job, all of the joins were written with WHERE clauses, and I was used to the INNER JOIN syntax (and SQL Server). I've now become fond of WHERE clauses for joins, but it's important to know both forms when working with different DBMSs.
Jim Schubert
ya, both work well. I prefer the INNER JOIN syntax just because its easier to read (I think)
Miles
A: 

The following assumes you have a column in the Order_Details table called OrderDetailID. If not, just substitute for the unique identifier for the order detail record.

SELECT COUNT(DISTINCT OD.OrderDetailID)
FROM Orders O
  LEFT JOIN Order_Details OD on (OD.OrderId = O.OrderId)
WHERE O.CustomerID = "123"
Chris Lively