sql - 在sqlserver中如何从每个组中获取最后一个值(时间)
问题描述
在 sql server 我有下面的表结构
basicid alertType alertTypeId alertDescription macId timeStamp companyId alertName alertCondition unitType channelType alertValue expectedValue
1234 406 123 test 13446 1547722123000 1234 test data test Centimeters length 50 60
1295 409 127 test 13448 1547722123000 1234 test data test Centimeters length 50.2 60.3
1298 409 128 test 13448 1547722123000 1234 test data test Centimeters length 50.2 60.3
1237 408 123 test 13446 1547722123000 1234 test data test Centimeters length 50.2 60.3
1255 409 128 test 13448 1548135899000 1234 test data test Centimeters length 50.2 60.3
1256 409 128 test 13448 1548135899000 1234 test data test Centimeters length 50.2 60.3
我正在尝试将具有最大时间戳的 alertType、alertTypeId、macid 分组(如果时间戳也相同,则每组应该只返回一个数据)。
我正在使用以下查询
SELECT a.basicid,
a.[alertType],
a.[alertTypeId],
a.[macId],
MAX(a.timeStamp) as t
FROM [test].[dbo].[alertdetails] as a
GROUP BY a.[alertType], a.[alertTypeId], a.[macId], a.basicid
ORDER BY a.basicid
但是正在返回所有数据。
我想要的最终数据是
basicid alertType alertTypeId alertDescription macId timeStamp companyId alertName alertCondition unitType channelType alertValue expectedValue
1234 406 123 test 13446 1547722123000 1234 test data test Centimeters length 50 60
1295 409 127 test 13448 1547722123000 1234 test data test Centimeters length 50.2 60.3
1237 408 123 test 13446 1547722123000 1234 test data test Centimeters length 50.2 60.3
1256 409 128 test 13448 1548135899000 1234 test data test Centimeters length 50.2 60.3
解决方案
您可以使用ROW_NUMBER()
以下查询轻松完成此操作。
SELECT *
FROM (SELECT *,
Row_number()
OVER(
partition BY alerttype, alerttypeid, macid
ORDER BY timestamp DESC) RN
FROM [test].[dbo].[alertdetails]) T
WHERE rn = 1
推荐阅读
- javascript - 当'this'作为参数从外部js文件传递给函数时如何访问控件的ID
- swift - UIAlertView 对于基于 UIScene 的应用程序已弃用且不可用,请使用 UIAlertController
- scala - 计算 Map[String, BigInt] 的总和
- python - 从火花数据框到熊猫数据框
- sas - 转换为 date5。SAS 格式
- python - 如何使用 wand python 将扫描的 pdf 转换为文本
- reactjs - 如何让反应只渲染组件的一部分?
- python - 开启 dropout 时验证损失减少
- python - 无法复制 openpyxl.Workbook 对象
- android - 将其移动到另一台计算机后无法构建我的android项目