我希望将s-id = 1>>>>相关性值的数量更新为2
(s-id)(relevancy)
0 null
0 null
3 2
4 null
4 null
4 null
4 null
5 2
9 null
这是我的代码:
SELECT s-id,COUNT(s-id) from ccc
group by s-id
update ccc set Relevancy=2 where COUNT(s-id)=1
但我认为聚合函数不能在where子句中使用,我现在应该怎么做?
答案 0 :(得分:2)
UPDATE ccc SET Relevancy = 2
WHERE (SELECT COUNT(*) FROM ccc c2 WHERE c2.[s-id] = ccc.[s-id]) = 1
Demo (最后一行的Relevancy
更新为2,因为9是唯一的)
另一种选择是CTE
使用COUNT(*)OVER
:
WITH CTE AS
(
SELECT [s-id], Relevancy,
CNT = COUNT(*) OVER (PARTITION BY [s-id])
FROM CCC
)
UPDATE CTE SET Relevancy = 2 WHERE CNT = 1
答案 1 :(得分:1)
update dbo.YourTable
set Relevancy = 2
where [s-id] in
(
select [s-id]
from dbo.YourTable
where Relevancy <> 2
group by
[s-id]
having count(*) = 1
)