简体   繁体   English

使用另一个表中的count更新

[英]update using count from another table

I want update wage in the staff table based on the staff members who have rented the most cars 我希望根据租车最多的员工在员工表中更新工资

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

The innermost query finds the highest number of cars rented by any member of staff. 最里面的查询查找任何员工租用的汽车数量最多。 This number is used in a having - to identify all the members of staff that rented that number of cars. 这个数字是在使用having -以确定租用这个数字轿车的所有工作人员。 That query is then join ed back onto the staff table to filter just the staff with a burning desire to rent cars - so that the update only gives them a pay rise. 然后将该查询join到员工表中,以过滤那些急需租车的员工 - 这样update只会让他们加薪。

You don't specify the database you are using, but you want something like this: 您没有指定您正在使用的数据库,但是您需要这样的内容:

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

This is SQL Server syntax, but similar constructs work in most databases. 这是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)
);

I did not test it, hope it helps. 我没有测试它,希望它有所帮助。

Good luck. 祝好运。

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

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