SQL - 根据表中行中其他字段的计数更新字段

时间:2013-10-09 19:55:55

标签: sql sql-server sql-server-2008

我有一个表[申请者],其中包含以下字段:

1)会员ID 2)尝试

我的一些尝试是NULL。

我想将表中的MemberID计数为1的行更新尝试字段为0。

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

一般方法是

update applicants set
    Attempts = 0
where
    MemberID in (select t.MemberID from applicants as t group by t.MemberID having count(*) = 1) and 
    Attempts is null -- if you need it

在sql server中你可以做类似的事情:

with cte as (
    select *, count(*) over(partition by MemberID) as cnt
    from applicants
)
update cte set
   Attempts = 0
where cnt = 1 and Attempts is null

答案 1 :(得分:0)

UPDATE applicants
SET Attempts = 0
WHERE MemberID IN
     (SELECT MemberID FROM applicants GROUP BY MemberID HAVING COUNT(MemberID)=1)
  AND Attempts IS NULL