如果我的SQL Server表中存在重复的值,如何更新一点?
我有一个非常简单的表,在某一行中有一些重复的值,当该行有重复的值时,我想将一个位列更新为1,如果没有重复项,则更新为0。该表如下所示:如果我的SQL Server表中存在重复的值,如何更新一点?,sql,sql-server,Sql,Sql Server,我有一个非常简单的表,在某一行中有一些重复的值,当该行有重复的值时,我想将一个位列更新为1,如果没有重复项,则更新为0。该表如下所示: id name billingId mergeable ----------------------------------- 1 David 1234 (null) 2 Bill 1234 (null) 3 Sue 5342 (null) 4 Joe 9864
id name billingId mergeable
-----------------------------------
1 David 1234 (null)
2 Bill 1234 (null)
3 Sue 5342 (null)
4 Joe 9864 (null)
5 George 9864 (null)
6 George 9864 (null)
7 Emma 6757 (null)
我尝试过使用COUNT*并查找所有重复的行,但我很难更新BIT列
这看起来应该很容易,但使用lag对我不起作用。最基本的小提琴是
我预计结果如下:
id name billingId mergeable
----------------------------------
1 David 1234 1
2 Bill 1234 1
3 Sue 5342 0
4 Joe 9864 1
5 George 9864 1
6 George 9864 1
7 Emma 6757 0
您似乎想要一个窗口功能:
select t.*,
(case when count(*) over (partition by billingid) > 1
then 1 else 0
end) as mergeable
from t;
如果要在更新中使用此选项:
with toupdate as (
select t.*,
(case when count(*) over (partition by billingid) > 1
then 1 else 0
end) as new_mergeable
from t
)
set mergable = new_mergeable;
因此,如果我这样做,我将不得不使它成为一个临时表,然后在下一个查询中更新我的原始表,以使可合并列正确吗?嗯,实际上,无论发生什么情况,它都返回1。应为select t.*,当通过billingid对分区进行计数*大于1时,则为1,否则为0,可从用户t中合并;>1不大于0