I have following sample database schema
https://i.stack.imgur.com/EKNxY.jpg

I want:
A) All sales, group by Users.
B) Discounts, group by users.
I am using following queries:
FOR A:
SELECT u.UserID, u.UserName, Sum(d.Quantity * i.Price) AS 'Sales'
FROM OrderDetails d
INNER JOIN Orders o ON o.OrderID = d.OrderID
INNER JOIN Item i ON i.ItemID = d.ItemID
INNER JOIN [User] u ON u.UserID = o.UserID
GROUP BY u.UserID, u.UserName
RESULT:
UserID UserName Sales
1 Mobeen 11060
2 Cashier 25960
FOR B:
SELECT u.UserID, u.UserName, Sum(r.DiscountAmount) AS Discounts
FROM Receipt r
INNER JOIN Orders o ON o.OrderID = r.OrderID
INNER JOIN [User] u ON u.UserID = o.UserID
GROUP BY u.UserID, u.UserName
RESULT:
UserID UserName Discounts
1 Mobeen 50
2 Cashier 310
BUT Then I decided to combine both queries but now the problem is that I am getting different results.
The query is as below:
SELECT u.UserID,
u.UserName,
Sum(d.Quantity * i.Price) AS 'Sales',
Sum(r.DiscountAmount) AS 'Discounts'
FROM OrderDetails d
INNER JOIN Orders o ON o.OrderID = d.OrderID
INNER JOIN Item i ON i.ItemID = d.ItemID
INNER JOIN [User] u ON u.UserID = o.UserID
INNER JOIN Receipt r ON r.OrderID = o.OrderID
GROUP BY u.UserID, u.UserName
Result:
UserID UserName Sales Discounts
1 Mobeen 2270 50
2 Cashier 25760 430
The problem is that you are summing along multiple dimensions. If you want to combine them, use subqueries:
I think what is happening is that you are multiplying the receipt records for each item. You need to be very careful when bringing together data naively using joins. For such aggregations, subqueries are your friend.
If you need to get all the rows (i.e., there may be mismatches on either side), switch the join to a
full outer joinand use: