哪个店铺的工人注册人数超过实际产能?

时间:2015-03-30 17:29:31

标签: mysql

哪家店铺的工人注册人数超过其实际容量?

我有三张桌子

Shop(shopid,shopname,shopcapacity)
Workers(workerid,name,address)
Registration(regid,workerid,shopid,fromdate,todate)

我尝试了下面的查询,它适用于一个商店注册的工人数超过其容量的商店 - 但它不适用于每个商店,有人可以建议吗?

select shopname AS ShopName, 
shopcapacity AS ShopCapacity,
count(r.shopid) AS RegisteredWorkers
from shop f
inner join registration r
on f.shopid = r.shopid
where f.shopcapacity <  ANY ( select count(shopid) 
from registration
group by shopid)
group by r.shopid;

1 个答案:

答案 0 :(得分:0)

以下内容应该可以解决问题:

SELECT
    shopname
FROM
    shop
    LEFT OUTER JOIN registration reg on 
        shop.shopid = reg.shopid
    LEFT OUTER JOIN workers on
        reg.workerid = workers.workerid
WHERE CURDATE() BETWEEN reg.fromdate and reg.todate
HAVING count(distinct workerid) > shopcapacity
GROUP BY shopname, shopcapacity

我添加了WHERE CURDATE()...的位,因为您的registration表似乎是时间敏感的。

无论如何,此处的HAVING声明将检查当前注册的工作人员数量是否大于shopcapacity。 GROUP BY确保数据库在shopnameshopcapacity之间进行汇总。