I have (again) this tables:
User:
id | name
-------------
1 | 'John'
2 | 'Peter'
3 | 'Luke'
Accounts:
id | userid | amount | date
--------------------------
1 | 1 | 1000 | '2012-01-26'
2 | 1 | 2000 | '2011-12-25'
3 | 1 | 1000 | '2012-01-25'
4 | 2 | 1500 | '2012-01-15'
5 | 3 | 2500 | '2011-11-30'
I need to collect data, so I have, at the same time, a resultset with the users, the count of accounts for each user, the sum of the amounts for the accounts for each user, and also, the count of accounts for each user, but only that have a date only on the present year…
Something like this:
Some-query:
UserName | CountAccts | SumAccts | CountAcctsThisYear
-----------------------------------------------------
'John' | 3 | 4000 | 2
'Peter' | 1 | 1500 | 1
'Luke' | 1 | 2500 | 0
I manage to get the first 3 columns with this query:
SELECT u.name as Username,
COUNT(a.id) as CountAccts,
SUM(a.amount) as SumAccts
FROM User u
LEFT JOIN Accounts a ON u.id = a.userid
GROUP BY u.id;
Also, I can get the first and last columns with this other one:
SELECT u.name as Username,
COUNT(acctsthisyear.id) as CountAcctsThisYear
FROM User u
LEFT JOIN (SELECT a.id
FROM Accounts a
WHERE DATE_FORMAT(a.date,'%Y') = DATE_FORMAT(CURDATE(),'%Y')
) AS acctsthisyear ON u.id = acctsthisyear.userid
GROUP BY u.id;
But, here’s the problem, I can’t manage to use this two queries in such a way to get the final result I’m expecting…
I have…
– tried to left join the Accounts table and the acctsthisyear subquery with the User table (grouping by the us.id field), but all I get is something like this:
UserName | CountAccts | SumAccts | CountAcctsThisYear
-----------------------------------------------------
'John' | 6 | 6000 | 6
'Peter' | 1 | 1500 | 1
'Luke' | 0 | 0 | 0
(can’t remember all of the details, but the thing is that, for example, the 2 results for ‘John’ in CountAcctsThisyear, get duplicated too in the result, and all gets multiplied…)
- tried each query as a subquery:
SELECT * FROM
(first query with u.id as ufid also selected) AS first,
(second query with u.id as usid also selected) AS second
GROUP BY ufid, usid
and got something like this:
UserName | CountAccts | SumAccts | CountAcctsThisYear
-----------------------------------------------------
'John' | 3 | 4000 | 2
'Peter' | 1 | 1500 | 2
'Luke' | 1 | 2500 | 2
'John' | 3 | 4000 | 1
'Peter' | 1 | 1500 | 1
'Luke' | 1 | 2500 | 1
'John' | 3 | 4000 | 0
'Peter' | 1 | 1500 | 0
'Luke' | 1 | 2500 | 0
(and if I invert the Group by elements, all I get is the same but grouped in a different order…)
Any way… That’s it… any ideas of what is the right way to achieve what I’m looking for? I’m really frustrated with it, since I’m really no expert on SQL, specially on Joins :-/
try this: