Yawning Milk Yawning Milk - 2 months ago 5x
MySQL Question

SQL select sum with multiple where from different tables

So I have two tables in my MySQL, users and purchases.

User table contains Id, Name, Surname and so on. Purchase table contains Id, User_id, Status and Sum payed for something.

What I need is to get select from these two tables where I would have the sum of every item each user has buyed.

I've tried this with table 'users':

LEFT JOIN 'purchases'
ON 'users'.'id' = 'purchases'.'user_id'
SELECT SUM (sum) FROM 'users', 'purchases' WHERE 'purchases'.'status' = 'completed' AND 'purchases'.'user_id' = 'users'.'id'

But with this I get the same sum for each user, which is wrong. What should I write instead?

Would highly appreciate any possible help!

To provide some actual example, lets take this one:

Id: 1 Name: John
Id: 2 Name: Ann
Id: 10 Status: completed User_id: 1 Sum: 4.00
Id: 20 Status: completed User_id: 1 Sum: 8.00
Id: 30 Status: completed User_id: 2 Sum: 50.00
Id: 40 Status: completed User_id: 2 Sum: 100.00

After running the query I should get this:

Id: 1 Sum: 12.00
Id: 2 Sum: 150.00

The query was made via Laravel, so I had just

DB::table('users')->leftJoin... ->select(DB::raw...


Original Answer

First off, your submitted SQL was a mess, things were completely out of the conventional order, I'm not sure it would execute as presented. That said, this should do what you want, assuming I understand your desired output correctly:

SELECT users.id, users.name, users.surname, ROUND(SUM(purchases.sum),2) AS totalSum
FROM purchases
    LEFT JOIN users ON users.id = purchases.user_id
WHERE status='completed'
GROUP BY users.name, users.surname
ORDER BY users.id

The key aspect you were missing from your query was the GROUP BY section, I added ORDER BY for my own benefit on my fiddle, use it if you wish, or not.

Here's a fiddle I prepped for you prior to your posting of your sample data, the main answer has been given by others I see so I'm just posting this because I already did the work on it. http://sqlfiddle.com/#!9/8fa2d/6/0

Answer 2.0

Fiddle is acting up so this is untested but give it a try.

SELECT users.id, users.name, users.surname, ROUND(SUM(CASE WHEN purchases.status = 'completed' THEN purchases.sum ELSE 0 END),2) AS totalSum 
FROM users 
    LEFT JOIN purchases ON users.id = purchases.user_id 
GROUP BY users.id
ORDER BY users.id