sql server 一对多只取第一条 row_number() over (partition by XX order by YY )
需求:
当前有一张报警表 ,一张处理过程表(设备发生报警-->推送给XX-->XX已解决)。一个报警对应多条处理过程。如果查询只想要设备报警原因如何实现。
首先我们按隐患ID排下序更清楚的了解表的一对多结构,以及我们想要获取什么样的数据。
select RecordID,Name,[Time] from Alerts_Details order by RecordID desc
实现:
row_number() over (partition by XX order by YY )
显示序号列,按XX分组,按YY排序
select RecordID,Name, row_number() over (partition by RecordID order by seqnum) as group_idx from Alerts_Details
结果展示:
接下来我们只需要取出序号列编号为1的就可以了
select d.* from( select RecordID,Name, row_number() over (partition by RecordID order by seqnum) as group_idx from [REG.N6.IFI.Alerts].[dbo].Alerts_Details ) d where d.group_idx=1
最终结果展示: