Click here to Skip to main content
15,566,615 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am struggling to get the output in the following format:
| Total | Roles | Month | Year |
| 52    | Admin |January| 2012 |
| 0     | Tester|July   | 2012 |
| 41    | HR    |January| 2014 |
| 0     | TL    |June   | 2015 |
| 14    | VP    |March  | 2011 |

I am having two tables(say users and userType), here "type" column in users table is reference to userType table.

I want to get all the rows from right joined table and if there are no values in the left table then it should display "0".

Kindly suggest me your ideas to get the query for the above provided output.

Thank you in advance.

What I have tried:

Please view below which I have tried:

SELECT COALESCE(COUNT(u.`userId`),0) AS 'Total',r.`roleName` AS 'Role',COALESCE(MONTH(u.`userOn`),0) AS 'Month', COALESCE(YEAR(u.`userOn`),0) AS 'Year' FROM `users` u RIGHT JOIN `usertype` r ON u.`userRole` = r.`roleId` WHERE YEAR(`userOn`) > 2011 and u.`userRole` = r.`roleId` GROUP by r.`roleName`;
Updated 7-Jan-21 1:31am
Maciej Los 7-Jan-21 2:57am    
Sample data would be helpful.
This means that we need input data (tables: users and usertype).
I'd suggest to create db_fiddle.

1 solution

You need to understand how left / right joins work.

For rows in the usertype table with no corresponding rows in the users table, all columns from the users table will be NULL.

Your WHERE clause will then remove those rows, since YEAR(u.`userOn`) will be NULL, and u.`userRole` will be NULL. Neither condition in your WHERE clause will match those rows.

Move your conditions to the JOIN clause instead. NB: You've already specified the roleId match, so you don't need to specify that again.
SELECT COALESCE(COUNT(u.`userId`), 0) As 'Total', r.`roleName` As 'Role' FROM `users` u RIGHT JOIN `usertype` r ON u.`userRole` = r.`roleId` And YEAR(u.`userOn`) > 2011 GROUP BY r.`roleName`;
NB: The month and year columns do not make any sense. You're grouping the users by role name, so there could be multiple values for these columns. Which single value are you expecting to appear here? You will need to use an aggregate function to pick the correct one.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900