cseasy
07-20-2006, 04:08 PM
Hi,
I have a table with a DATETIME field to log activity.
I want to write a query that returns (up to) the most recent five unique months of activity, but that also shows my the total number of unique months so that if there are more than 5, I can show a 'more' button in my application.
The query I started with is:
SELECT
DATE_FORMAT(activityDate, '%M, %Y') AS activityDate, COUNT(DATE_FORMAT(activityDate, '%M, %Y')) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
GROUP BY
DATE_FORMAT(activityDate, '%M, %Y')
ORDER BY
activityDate DESC
LIMIT
5
But this only shows the qty as the number of items within the month in that row.
So then I tried:
SELECT
DATE_FORMAT(activityDate, '%M, %Y') AS activityDate, COUNT(*) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
GROUP BY
DATE_FORMAT(activityDate, '%M, %Y')
UNION
SELECT DISTINCT
'total' AS activityDate, COUNT(DATE_FORMAT(activityDate, '%M, %Y')) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
ORDER BY
activityDate DESC
LIMIT
6
This gives me a row at the top of my recordset with 'total' in the 'activityDate' field, but the 'qty' field shows a total of all unique dates, not just 'month, year' (so for example, if I have three items in July '06, instead of counting July '06 as 1 it's adding 3 to the total, essentially ignoring my DISTINCT.)
I'm sure I'm missing something extremely obvious and any help would be greatly appreciated.
Thanks,
C.
I have a table with a DATETIME field to log activity.
I want to write a query that returns (up to) the most recent five unique months of activity, but that also shows my the total number of unique months so that if there are more than 5, I can show a 'more' button in my application.
The query I started with is:
SELECT
DATE_FORMAT(activityDate, '%M, %Y') AS activityDate, COUNT(DATE_FORMAT(activityDate, '%M, %Y')) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
GROUP BY
DATE_FORMAT(activityDate, '%M, %Y')
ORDER BY
activityDate DESC
LIMIT
5
But this only shows the qty as the number of items within the month in that row.
So then I tried:
SELECT
DATE_FORMAT(activityDate, '%M, %Y') AS activityDate, COUNT(*) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
GROUP BY
DATE_FORMAT(activityDate, '%M, %Y')
UNION
SELECT DISTINCT
'total' AS activityDate, COUNT(DATE_FORMAT(activityDate, '%M, %Y')) AS qty
FROM
activity
WHERE
activityDate <= '2006-07-20 00:00:00'
ORDER BY
activityDate DESC
LIMIT
6
This gives me a row at the top of my recordset with 'total' in the 'activityDate' field, but the 'qty' field shows a total of all unique dates, not just 'month, year' (so for example, if I have three items in July '06, instead of counting July '06 as 1 it's adding 3 to the total, essentially ignoring my DISTINCT.)
I'm sure I'm missing something extremely obvious and any help would be greatly appreciated.
Thanks,
C.