繁体   English   中英

使用另一个表中的count更新

[英]update using count from another table

我希望根据租车最多的员工在员工表中更新工资

UPDATE staff 
SET wage = wage + 5000 

WHERE COUNT(staffid) >= ALL
Select COUNT(staffid) FROM carforrent)
update s set
    s.wage = s.wage + 5000 
from staff s
join (
    select staffid
    from carforrent
    group by staffid
    having count(*) = (
        select top 1 count(*)
        from carforrent
        group by staffid
        order by count(*) desc
    )
) sq on sq.staffid=s.staffid

最里面的查询查找任何员工租用的汽车数量最多。 这个数字是在使用having -以确定租用这个数字轿车的所有工作人员。 然后将该查询join到员工表中,以过滤那些急需租车的员工 - 这样update只会让他们加薪。

您没有指定您正在使用的数据库,但是您需要这样的内容:

update staff
    set wage = wage + 5000
    where staffid in (select top 1 staffid
                      from carforrent
                      group by staffid
                      order by count(*) desc
                     );

这是SQL Server语法,但类似的结构在大多数数据库中都有效。

with cte
as
(
    select top 1 count(1) maxcount
    from carforrent
    group by staffid
    order by count(1) desc
)
update staff
set wage = wage + 5000
where staffid in(
    select staffid
    from carforrent
    group by staffid
    having count(1) = (select maxcount from cte)
);

我没有测试它,希望它有所帮助。

祝好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM