T-SQL - 如果没有列条目,则更新任何重复行

时间:2017-06-26 07:40:38

标签: sql tsql

我有一张表格,我喜欢更新每个 NAME 只有一个 ACTIVE 条目。订单无关紧要。

鉴于表:

| NAME   | ACTIVE |
|-----------------|
| Adam   | 0      |
| Adam   | 0      |
| Peter  | 0      |
| Peter  | 0      |
| Peter  | 0      |
| Mike   | 1      |
| Mike   | 0      |
| Phil   | 1      |
| Phil   | 1      |

期望的结果:

| NAME   | ACTIVE |
|-----------------|
| Adam   | 1      |
| Adam   | 0      |
| Peter  | 1      |
| Peter  | 0      |
| Peter  | 0      |
| Mike   | 1      |
| Mike   | 0      |
| Phil   | 1      |
| Phil   | 0      |

我会开始将 ACTIVE 设置为" 0"在每一行上删除重复项,如 Phil 行。

UPDATE TABLE SET ACTIVE=0

但是我如何设法只将每个名字设置为活动一次?

2 个答案:

答案 0 :(得分:1)

这就是我的方法:
我为每个组创建一个rownumber(名称)
最后只需将rownumber = 1的行设置为活动,其他所有行设置为0 =不活动

UPDATE UpdateTarget
   SET ACTIVE = IIF(RowNum = 1, 1, 0) -- set first occurance to active, others inactive
  FROM ( SELECT *
               ,ROW_NUMBER() OVER(PARTITION BY NAME ORDER BY x.NAME) AS RowNum
           FROM mytable x
       ) AS UpdateTarget
 ;

我还创建了一个Rextester,所以你可以测试我的脚本: http://rextester.com/YWCOT10468

答案 1 :(得分:1)

您可以通过这种方式更新表格,如果您想删除重复项,请使用第二个查询或从查询中选择不同的记录

with t as
(
select *, ROW_NUMBER() over ( partition by name order by name ) row from YourTable t
) 

update t 
set active = case when row = 1 then 1 else 0 end 

; 

- 删除重复记录

with t as
(
select *, ROW_NUMBER() over ( partition by name order by name ) row from YourTable t
) 

delete t where row > 2
;

select * from YourTable