I am working to achieve the Highcharts dynamic graph - the base column, and I need help creating SQL in MySQL. I need results for the last 12 months (regardless of any data for the month (maybe 0 - but all 12-month records should be received)) from the current month, showing how many participants (4 types of users) registered on the site for a particular month.
There are 4 types of users:
- Agents
- Individuals
- Builders
- Real Estate Companies
For the Months column, it should get the last 12 months from the current month - August, September, October, November, December, January, February, March, April, May, June, July.
I tried with the following query:
SELECT CASE WHEN u.`userTypeID`=1 THEN COUNT(`userTypeID`) ELSE 0 END AS agent, CASE WHEN u.`userTypeID`=2 THEN COUNT(`userTypeID`) ELSE 0 END AS individuals, CASE WHEN u.`userTypeID`=3 THEN COUNT(`userTypeID`) ELSE 0 END AS builders, CASE WHEN u.`userTypeID`=4 THEN COUNT(`userTypeID`) ELSE 0 END AS real_estate_companies, u.`userRegistredDate` AS 'timestamp' FROM `dp_users` AS u LEFT JOIN `dp_user_types` AS ut ON u.`userTypeID` = ut.`type_id` WHERE u.`userRegistredDate` < Now( ) AND u.`userRegistredDate` > DATE_ADD( Now( ) , INTERVAL -12 MONTH ) GROUP BY DATE_FORMAT( u.`userRegistredDate`, '%b' )
Output (wrong):
| AGENT | INDIVIDUALS | BUILDERS | REAL_ESTATE_COMPANIES | TIMESTAMP | ---------------------------------------------------------------------------------------- | 0 | 0 | 9 | 0 | July, 01 2013 17:14:35+0000 | | 3 | 0 | 0 | 0 | May, 15 2013 14:14:26+0000 |
Output (required: correct):
| AGENT | INDIVIDUALS | BUILDERS | REAL_ESTATE_COMPANIES | TIMESTAMP | ---------------------------------------------------------------------------------------- | 3 | 2 | 2 | 2 | July, 01 2013 17:14:35+0000 | | 1 | 2 | 0 | 0 | May, 15 2013 14:14:26+0000 |
Another way I tried was with a subquery, please find both links below:
http://sqlfiddle.com/#!2/ed101/53 http://sqlfiddle.com/#!2/ed101/54
Hoping to find a favorable solution, thanks.