SQL 合并某些字段相同的记录

在数据表FlowBusinessData.dbo.AOC_Abnormal_Main中,针对register和reason不同的相同记录,通过创建临时表并进行表连接,选取register值最大的记录。首先,根据特定条件对数据进行分组,然后将临时表与原始表连接,以保留每个分组的最大register值对应的完整信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 在数据表t1中存在记录

          

classname   classnum studentname     latetime register reason
高二(3)班    06023王强        8.12     8.15   班车没赶上
  高二(3)班  06023 王强  8.17     8.22  又没赶上
  高二(6)班   06026  陈东    817    8.22    掉水沟里了
  高二(3)班 06023 王强    8.12   8.17   null

 

 要得到的记录如下:

classname   classnum studentname     latetime register reason
  高二(3)班  06023 王强  8.17     8.22  又没赶上
  高二(6)班   06026  陈东    817    8.22    掉水沟里了
  高二(3)班 06023 王强    8.12   8.17    班车没赶上

   就是如果有两笔资料都一样只是register和reason不同,那么取register大的一笔。我的做法是

  先创建临时表,然后再通过表连接得到对应的reason

  

     create table #cards (
     DeptName nvarchar(50),
     EmpyNo NVARCHAR(15),
     Uname nvarchar(20),
     ADate nvarchar(50),
     MaxIdate datetime
     )
    insert #cards
 select t1.DeptName,t1.EmpyNO,t1.Uname,convert(nvarchar(100),t1.ADate,102) as ADate,max(t1.idate) as maxidate1
 from [FlowBusinessData].[dbo].[AOC_Abnormal_Main] t1 
 where  PCode_level in('12','13') and month(adate)=month(getdate())-1 and inflow='T' 
 group by t1.ADate ,t1.DeptName,t1.EmpyNO,t1.Uname
 

 select t2.DeptName,t2.EmpyNO,t2.Uname,t2.empyno,convert(nvarchar(100),t2.ADate,102) as ADate,t2.Errtype,t2.CardTS,t2.CardTE,t2.idate,t2.BAK
 from [FlowBusinessData].[dbo].[AOC_Abnormal_Main] t2 ,#cards
 where #cards.empyno=t2.empyno   and #cards.adate=convert(nvarchar(100),t2.ADate,102)  and #cards.MaxIdate=t2.idate
 group by t2.ADate ,t2.empyno,t2.DeptName,t2.EmpyNO,t2.Uname,t2.Errtype,t2.CardTS,t2.CardTE,t2.BAK,t2.idate
 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值