Sql server 2012 SQL列重复值计数
我有一张学生桌。目前它有许多列,如Sql server 2012 SQL列重复值计数,sql-server-2012,Sql Server 2012,我有一张学生桌。目前它有许多列,如ID,StudentName,FatherName,NIC,MotherName,无子女,职业等 我想检查插入时间的NIC字段。如果是重复的,则对重复的NIC进行计数,并在No\u of_Children列中添加计数编号 在SQL Server中执行此操作的最佳方法是什么?听起来您需要一个升级。在SQL中实现这一点的最简洁的方法(我知道)是通过合并操作 declare @students table ( NIC int ,No_Of_Childrens i
ID
,StudentName
,FatherName
,NIC
,MotherName
,无子女
,职业
等
我想检查插入时间的NIC
字段。如果是重复的,则对重复的NIC
进行计数,并在No\u of_Children
列中添加计数编号
在SQL Server中执行此操作的最佳方法是什么?听起来您需要一个升级。在SQL中实现这一点的最简洁的方法(我知道)是通过合并操作
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;
若要在插入数据时执行此操作,则必须创建一个触发器,若在学生表中插入数据,将触发该触发器。触发器将检查NIC的数据是否重复,如果是,则将在子项列的“否”中添加计数。。