使用另一个表中的count更新

时间:2013-12-04 22:18:16

标签: sql count

我想根据租车最多的员工

在员工表中更新工资
UPDATE staff 
SET wage = wage + 5000 

WHERE COUNT(staffid) >= ALL
Select COUNT(staffid) FROM carforrent)

3 个答案:

答案 0 :(得分:2)

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只会让他们加薪。

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

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)
);

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

祝你好运。