I am struggling to get the output in the following format: eg
| 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".
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`;
How to get the query for the provided output?
Put your YEAR(userOn) > 2011
condition in ON Clause
like below
SELECT COALESCE(COUNT(u.`userId`),0) AS 'Total',r.`roleName` AS 'Role'
FROM `usertype` r left join `users` u ON u.`userRole` = r.`roleId`
and YEAR(`userOn`) > 2011
GROUP by r.`roleName`;
Coalesce
is not required and you can do right join
as follows:
SELECT COUNT(u.`userId`) 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`;
You will have to write the condition YEAR(u.userOn) > 2011
in ON
clause
It is also possible to solve this with a subquery. Something like this:
Select
(select count(*) from users where userRole=roleId and YEAR(`userOn`) > 2011),
rolename as Role
from usertype
Functions cannot use indexes, so if useron is part of an index (and it certainly should be) then something like this will be more efficient:
SELECT COALESCE(COUNT(u.userId),0) Total
, r.roleName Role
FROM usertype r
LEFT
JOIN users u
ON u.userRole = r.roleId
AND u.userOn >= '2011-01-01'
GROUP
BY r.roleName
An index on some combination of (userOn,userRole) seems sensible
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.