SQL列重复值计数

时间:2015-08-14 14:52:17

标签: sql-server-2012

我有一张Student表。目前,它有很多列,例如IDStudentNameFatherNameNICMotherNameNo_Of_ChildrensOccupation等。< / p>

我想在插入时检查NIC字段。如果它是重复的,则计算重复的NIC并在No_of_Children列中添加计数。

在SQL Server中执行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

听起来你想要一个UPSERT。在SQL(我知道)中实现这一目标的最简洁方法是通过MERGE操作。

declare @students table
(
  NIC int
 ,No_Of_Childrens int
);

--set up some test data to get us started
insert into @students
      select 12345,1
union select 12346,2
union select 12347,2;

--show before
select * from @students;

declare @incomingrow table(NIC int,childcount int);
insert into @incomingrow values (12345,2);

MERGE 
  --the table we want to change
  @students AS target  
USING 
  --the incoming data
  @incomingrow AS source
ON 
  --if these fields match, then the "when matched" section happens.
  --else the "when not matched".
  target.NIC = source.NIC
WHEN MATCHED THEN 
  --this statement will happen when you find a match.
  --in our case, we increment the child count.
  UPDATE SET NO_OF_CHILDRENS = no_of_childrens + source.childcount
WHEN NOT MATCHED THEN 
  --this statement will happen when you do *not* find a match.
  --in our case, we insert a new row with a child count of 0.
  INSERT (nic,no_of_childrens) values(source.nic,0);

--show the results *after* the merge
select * from @students;