sql - 如何获取每组具有最大时间戳的每条记录
问题描述
在 SQL Server 中,我有下面的表结构
alert_details_status表:
alertTypeId macId timeStamp is_notified escalation_status alertType
123 13446 1547722123000 true completed 408
alert_details表:
basicid alertType alertTypeId alertDescription macId timeStamp companyId alertName alertCondition unitType channelType alertValue expectedValue
1234 406 123 testalert 13446 1547722123000 1234 test alert name testalert Centimeters length 50 60
1295 409 127 testalert 13448 1547722123000 1234 test alert name testalert Centimeters length 50.2 60.3
1298 409 128 testalert 13448 1547722123000 1234 test alert name testalert Centimeters length 50.2 60.3
1238 408 123 testalert 13446 1547722123000 1234 test alert name testalert Centimeters length 50.2 60.3
1255 409 128 testalert 13448 1548135899000 1234 test alert name testalert Centimeters length 50.2 60.3
1256 409 128 testalert 13448 1548135899000 1234 test alert name testalert Centimeters length 50.2 60.3
1251 408 123 testalert 13446 1548148705000 1234 test alert name testalert Centimeters length 50.2 60.3
如果alert_details_status
表记录timestamp >30 minutes(compared to present time)
对于每组alertTypeId
, macId
,alertType
具有is_notified
true 并且escalation_status
已完成,则应选择对应alertTypeId
的 , macId
,具有每个记录的最大时间戳(每组最多一条记录,即使组的时间戳相同)。alertType
如何得到上述结果。我尝试使用以下查询,但它什么也没返回。实际上它应该返回 1251 基本 id 记录,因为它在alert_details_status table having timestamp >30 min compared to present timestamp. So for that alertTypeId ,macId alertType it should return maximum of timestamp for a group having alertTypeId ,macId alertType(i,e 1251)
.
SELECT *
FROM (SELECT t1.*,
Row_number()
OVER(
partition BY t1.alerttype, t1.alerttypeid, t1.macid
ORDER BY t1.timestamp DESC) rn
FROM [test].[dbo].[alertdetails] as t1
RIGHT JOIN [test].[dbo].[alert_details_status] t2
ON t1.macid = t2.macid
AND t1.alerttypeid = t2.alerttypeid
AND t1.alerttype = t2.alerttype
AND t2.is_notified = 'true '
AND t2.escalation_status = 'completed'
WHERE ((DATEDIFF(s, '1970-01-01', GETUTCDATE())-(t2.timeStamp/1000))/60)>4400 and t2.alerttypeid IS NULL ) t
WHERE t.rn = 1
我想要的结果是:
basicid alertType alertTypeId alertDescription macId timeStamp companyId alertName alertCondition unitType channelType alertValue expectedValue
1251 408 123 testalert 13446 1548148705000 1234 test alert name testalert Centimeters length 50.2 60.3
解决方案
推荐阅读
- c# - 如何检查网络/共享文件夹的稳定性?
- javascript - 即使使用 extraData={this.state},PureComponent FlatList 也不会重新渲染
- c# - Gridview 保存数据会失去旧值
- mulesoft - 如何从 mule 中的不同属性(例如 - prop1_dev、prop2_stage、prop3_prod)读取属性文件值
- php - 如何修复,获取 jquery-2.2.4.min.js:4 错误 500?
- ios - 在 Swift iOS 中根据大小对文档目录中的文件和文件夹进行排序
- javascript - 从表格单元格中获取最大数字
- javascript - 按钮值在超时时更改回原始值(表单双重提交)
- javascript - 在 React 模态中插入 ID
- python - 在对大型 csv 文件进行分块时使用多处理来加快 pandas 的加载