So I want to compare new users to returning users in a table by month. I have a table that contains each action with a username and a date stamp.
I can easily pull users that performed an action in, for example, January 2011. To see see if each user is new I need to then run their username against all previous records (prior to January 2011).
In my fumblings I came up with the following:
SELECT ini.username,
MIN(ini.datetime) AS firstAction,
COUNT(ini.datetime) AS numMonth,
(SELECT COUNT(*)
FROM tableActions tot
WHERE tot.username = ini.username
AND tot.datetime < '201101%'
AND tot.datetime > '201001%') AS numTotal
FROM tableActions ini
WHERE DATETIME >= '201101%'
AND DATETIME < '201102%'
GROUP BY ini.username
ORDER BY firstAction
It doesn’t error, but it doesn’t finish either. Seems to be quite intense.
You can re-write the query to be (assuming
tableactions.datetimeis aDATETIMEdata type):Might help to have an index on
usernameat a minimum, though a covering index usingusername,datetimeis worth considering.The
datetimecomparison looks suspect –LIKEis the only to support wildcards.