2013-10-09 63 views
-1

我有一個表[報名]具有以下字段更新領域:SQL基於其他領域的計數行的表

1)MEMBERID 2)嘗試

我的一些嘗試是空值。

我想企圖場更新爲0的那些行,其中MEMBERID表中的計數爲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 
+0

感謝那些工作。但是,你爲什麼按MemberID分組? – vitalious

+0

'GROUP BY具有COUNT(MemberID)= 1'的GROUP BY允許獲得在組中計數的'MemberID'-s等於1。 –

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