I need make such request: choose list of cities which include letter i and have appropriate number of employees. Also I need take to attention that some city could have 0 employee and that for some employee field DEBT could be null.
Table depart
debt city
-------------
43 odesa
23 kiev
79 lviv
78 lviv
12 rivne
Table empl
ide fn ln debt
----------------------------
3421 jed trt 43
354 jed res 43
43 ged hjkhg 79
73 ghghg gfgf 79
456 jkl gdfg
532 kkhg vjv 23
45 ki vt
243 ki vt 78
I wrote this query:
select depart.CITY, count (*) as numb
from depart
inner join empl on empl.DEBT=depart.DEBT
where depart.CITY like '%i%'
group by depart.CITY;
But I do not know how take care about that some city could have 0 employee (for example this request does not show city rivne which have 0 employee) and that for some employee field DEBT could be null.
I use oracle with toad.
Expected results
city numb
kiev 1
rivne 0
lviv 3
To take care of criterion move
wherebefore group by. To allow for non-existing employees or null DEBT, use left outer join.To get all employees grouped by department you would reverse the outer join:
(Presumably
ideis primary key of employee).But this would not return departments without employees, and CITY would be null where department’s city would not match
%i%or empl.DEBT would be null from the start.To solve the problem, one might extend first query with union all designed to retrieve employees without departments. But there is a question: do we want only departmentless employees, or we consider or employees not working in a city whose name contains
idepartmentless also. I’ve opted for second possibility.If you need distinction between employees without departments and those who work in a city not containing
i, you might use case:This query will count employees from matching cities, unmatching cities and those who have no department.