carrying out arithmetic operation using data from two unrelated tables

144 views Asked by At

[Order Details] and [Customers] are both unrelated tables. Normally I would suppose that I can't make queries drawing from both of them, since the number of rows might not match.

However, in this case since SUM(od.quantity * od.Unitprice) and COUNT(distinct c.CustomerID) are both single integers, why can't I perform my query as shown below?

SELECT SUM(od.quantity * od.Unitprice) / COUNT(distinct c.CustomerID) 
FROM[Order Details] od, Customers c

sample data:

enter image description here

note: I'm using the Northwind sample database on microsoft sql server

1

There are 1 answers

2
Tab Alleman On BEST ANSWER

Due to the way your query is formatted with a single FROM clause and an old-style join, you are doing a CROSSJOIN which gets the cartesian product of every row joined to every row from the two tables.

To just get the single row you seem to be looking for, you need to use two subqueries:

 SELECT (SELECT SUM(od.quantity * od.Unitprice) FROM [Order Details] od)/(SELECT COUNT(distinct c.CustomerID) FROM Customers c)