我的数据:
STAFF
(id, name,outlet)
=====================
(1, 'John','WA'),
(2, 'Mary', 'WA'),
(3, 'Wilson', 'PH'),
(4, 'James', 'NY'),
OUTLET
(name, supervisorid)
============
('WA', 2),
('PH', 3),
('NY', 4),
我正在寻找以下输出
outlet,supervisorname,noofstaffinoutlet
WA,John,2
PH,Wilson,1
NY,James,1
我可以使用
计算员工人数 select s.outlet ,count(s.outlet) from STAFF s group by s.outlet;
如何添加插座的主管名称?
我尝试添加STAFF.id = OUTLET.superviorid
,但如果我这样做,我的计数就会变为1。
答案 0 :(得分:1)
您可以与员工联系两次 - 一次获取主管ID,一次在汇总查询中获取员工人数:
SELECT o.name, s.name, c.cnt
FROM outlet o
JOIN staff s ON s.id = o.supervisorid
JOIN (SELECT outlet, COUNT(*) AS cnt
FROM staff
GROUP BY outlet) c ON c.outlet = o.name
答案 1 :(得分:1)
加入let lst = sub_lst1@sub_lst2
两次。
staff
使用SELECT o.name AS outlet, s1.name AS supervisorname, IFNULL(COUNT(s2.id), 0) AS nooffstaffinoutlet
FROM outlet AS o
JOIN staff AS s ON o.supervisorid = s.id
LEFT JOIN staff AS s2 on o.name = s2.outlet
和LEFT JOIN
可以让查询显示IFNULL()
没有员工的商店。