I'm attempting to make a running total using months. Here's a simplified version of what I'm doing that partially works:
SELECT
MONTHNAME(STR_TO_DATE(DateContacted,'%m/%d/%Y')) AS MONTH,
IFNULL(COUNT(CASE WHEN s.surveyid = 649814 THEN s.id ELSE NULL END),0) Signer,
(SELECT COUNT(s2.id) FROM sq s2
WHERE s2.surveyid = 649814 AND MONTHNAME(STR_TO_DATE(s2.DateContacted,'%m/%d/%Y')) <= MONTH
GROUP BY MONTH
ORDER BY MONTH) RT
FROM
sq s
GROUP BY MONTH
ORDER BY MONTH
But the problem is that the order is off, which is obviously a big deal when you're trying to do a running total:
MONTH Signer RT
April 1646 1646
August 81 1727
December 0 1727
February 0 1727
January 0 1727
July 24 1751
June 241 1992
March 2120 4112
May 115 4227
November 28 4255
October 173 4428
September 73 4501
But when I attempt to order it properly like this:
SELECT
MONTHNAME(STR_TO_DATE(DateContacted,'%m/%d/%Y')) AS MONTH,
IFNULL(COUNT(CASE WHEN s.surveyid = 649814 THEN s.id ELSE NULL END),0) Signer,
(SELECT COUNT(s2.id) FROM sq s2
WHERE s2.surveyid = 649814 AND MONTHNAME(STR_TO_DATE(s2.DateContacted,'%m/%d/%Y')) <= MONTH
GROUP BY MONTH
ORDER BY FIELD(MONTH,'January','February','March','April','May','June','July','August','September','October','November','December')) RT
FROM
sq s
GROUP BY MONTH
ORDER BY FIELD(MONTH,'January','February','March','April','May','June','July','August','September','October','November','December')
It throws off all the RT counts (though the Signer counts are right):
MONTH Signer RT
January 0 1727
February 0 1727
March 2120 4112
April 1646 1646
May 115 4227
June 241 1992
July 24 1751
August 81 1727
September 73 4501
October 173 4428
November 28 4255
December 0 1727
I used this method instead of a subquery because this is normally part of a much larger query where I LEFT JOIN
two tables together by month. I also seemingly can't use the @runtot variable solution unfortunately because this needs to be GROUPed by month at the end and that throws it off. I know MySQL's not perfect for this kind of functions but I seem to be close and if this could be along with the rest of my query in the same place, that'd be great. Any help is appreciated!
Edit:
Here's the ideal end-table:
MONTH Signer RT
January 0 0
February 0 0
March 2120 2120
April 1646 3766
May 115 3881
June 241 4122
July 24 4146
August 81 4227
September 73 4300
October 173 4473
November 28 4501
December 0 4501