I have 3 tables in a query:
apiusers, users
- these contain a user id, and a name.
download_stats:
this contains usertype (1 = users, 2 = apiusers), date, file downloaded_id.
What I want to do is get a layout of:
| user id | name | download stats for january | download stats for february
etc.
I’m currently trying with this query, which takes forever:
SELECT name,queryuserid,count(ROWA.id) ,count(ROWB.id)
FROM (SELECT IFNULL(u.name, au.companyname) AS name,IFNULL(u.id, au.id) AS queryuserid
FROM apiusers as au, users as u
GROUP BY 2 ) AS users
LEFT JOIN stats_download as ROWA ON ROWA.userid=queryuserid AND ROWA.date > date('2011-01-01') AND ROWA.date < date('2011-02-01')
LEFT JOIN stats_download as ROWB ON ROWB.userid=queryuserid AND ROWB.date > date('2011-01-01') AND ROWB.date < date('2011-02-01')
GROUP BY 2;
Is there a better way of going about this? The client wants supports to “group” the output statistics by year, month and day. So there could potentionally be 30+ LEFT JOIN’s in there.
This should get you the basis, and runs an entire year sample. Look at the pattern. By doing a sum of a qualified IF() condition returning 1 or 0 you get the total count per each month. Now, if you are looking for SIZE (such as download size), instead of 1, 0, you can just substitute the fileSize instead of 1 and you’ll have the total downloaded size… put them as different columns and you can have both Count of downloads and totalSize of downloads. Expand the date range over year, just keep going with the pattern…