I have a table 'order' containing summary order information and a table 'orderItem' with each item of the order.
My issue is: when selecting the Sum of column 'orderQTY' from the 'Order' table, I get an incorrect total if i join the orderItem table.
The first query below gives me the correct total. However, as soon as I add the join to orderItem, the sum result is incorrectly duplicating the 'orderqty' column for each orderitem record.
nb: I know the below doesn't utilise the join and isn't necessary. I've removed the clauses referring to the joined table to simplify the question.
--RETURNS Correct value
select sum(o.orderqty)
from [order] o
--RETURNS the sum containing duplicates of o.orderqty
select sum(o.orderqty)
from [order] o
join OrderItem oi on o.Id = oi.OrderId
-- adding clarification: ----
I am wanting to Sum the column 'orderqty' from table 'order' while joining to orderItem eg:
There would be multiple orderItems for each Order, but I only want to obviously only count the orderqty from the order table once per order.
select sum(o.ordertotal)
from [order] o with(NOLOCK)
join OrderItem oi on o.Id = oi.OrderId
where oi.mycolumn = 1
or would i need to do something like:
select sum(o.ordertotal)
from [order] o with(NOLOCK)
where o.id in (select orderid from orderitem where x = y)