在 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 1548148705000 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
我正在尝试对具有最大时间戳
的alertType
、alertTypeId
、macid
进行分组(应该只返回一个每组的数据(如果时间戳也相同)来自alert_details,但不在alert_details_status中。在两个表中,alertType、alertTypeId、macid 应该不同,然后每个组只应显示具有最大时间戳的alert_details 的结果。
我正在使用以下查询
SELECT *
FROM
(SELECT
*,
ROW_NUMBER() OVER (PARTITINO BY alerttype, alerttypeid, macid ORDER BY timestamp DESC) RN
FROM
[test].[dbo].[alertdetails]) a
WHERE
rn = 1
AND NOT EXISTS (SELECT macId, alertTypeId, MAX(timestamp)
FROM [test].[dbo].[alert_details_status] AS c
WHERE a.macId = c.macId
AND a.alertTypeId = c.alertTypeId
AND a.alertType = c.alertType
AND (is_notified = 'true' AND escalation_status = 'completed')
GROUP BY alertTypeId, macId)
但它返回错误的数据。
我想要的最终数据是
basicid alertType alertTypeId alertDescription macId timeStamp companyId alertName alertCondition unitType channelType alertValue expectedValue
1295 409 127 testalert 13448 1547722123000 1234 test alert name testalert Centimeters length 50.2 60.3
1238 408 123 testalert 13446 1548148705000 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
最佳答案
您首先计算然后过滤数据,这可能是问题所在。您可以尝试先过滤数据,然后再计算。
您可以尝试如下查询。
SELECT *
FROM (SELECT t1.*,
Row_number()
OVER(
partition BY t1.alerttype, t1.alerttypeid, t1.macid
ORDER BY t1.timestamp DESC) rn
FROM alert_details
LEFT JOIN alert_details_status t2
ON macid = c.macid
AND t1.alerttypeid = t2.alerttypeid
AND t1.alerttype = t2.alerttype
AND t2.is_notified = true
AND t2.escalation_status = 'completed'
WHERE t2.alerttypeid IS NULL) t
WHERE t.rn = 1
关于sql - 在SQL Server中如何从不在另一个表中的每个组中获取最大时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54385967/