SQL查询获取最后一个记录按多个字段分组

时间:2019-08-09 13:29:05

标签: sql-server

嗨,我有一个包含以下字段的表格:

ALERTID POLY_CODE ALERT_DATETIME ALERT_TYPE

我需要在上表中查询过去24小时内的记录。 然后按POLY_CODE和ALERT_TYPE分组,并获得由ALERT_DATETIME排序的最新Alert_Level值 我可以解决这个问题,但是我需要结果记录的AlertID。 有什么建议可以有效地实现这一目标吗?

我已经在SQL Server中创建了一个SQL。见下文

SELECT POLY_CODE, ALERT_TYPE, X.ALERT_LEVEL AS LAST_ALERT_LEVEL
FROM
(SELECT * FROM TableA where ALERT_DATETIME >= GETDATE() -1) T1
    OUTER APPLY (SELECT TOP 1 [ALERT_LEVEL] 
    FROM (SELECT * FROM TableA where ALERT_DATETIME >= GETDATE() -1) T2 
    WHERE T2.POLY_CODE = T1.POLY_CODE AND
    T2.ALERT_TYPE = T1.ALERT_TYPE ORDER BY T2.[ALERT_DATETIME] DESC) X
GROUP BY POLY_CODE, ALERT_TYPE, X.[ALERT_LEVEL]

POLY_CODE       ALERT_TYPE      ALERT_LEVEL
04575       Elec        2
04737       Gas     3
06239       Elec        2
06552       Elec        2
06578       Elec        2
10320       Elec        2

2 个答案:

答案 0 :(得分:0)

一种方法是使用分组创建一个cte,该分组计算每个分组的latestdatetime,然后将其与表交叉以获取结果。请记住,如果有多个记录,并且poly_code,alert_type,alert_level和datetime的相同组合都将显示出来。

WITH list AS (
SELECT ta.poly_code,ta.alert_type,MAX(ta.alert_datetime) AS LatestDatetime,
    ta.alert_level
FROM dbo.TableA AS ta
WHERE ta.alert_datetime >= DATEADD(DAY,-1,GETDATE())
GROUP BY ta.poly_code, ta.alert_type,ta.alert_level
)
SELECT ta.*
FROM list AS l
INNER JOIN dbo.TableA AS ta ON ta.alert_level = l.alert_level AND ta.alert_type = l.alert_type AND ta.poly_code = l.poly_code AND ta.alert_datetime = l.LatestDatetime

答案 1 :(得分:0)

select top 1 with ties *
from TableA
where ALERT_DATETIME >= GETDATE() -1
order by row_number() over (partition by POLY_CODE,ALERT_TYPE order by [ALERT_DATETIME] DESC)

此方法的工作方式是,对于每个POLY_CODE,ALERT_TYPE组,从最近的alert_datetime开始,获取自己的row_number()。然后,with ties子句可确保返回row_number值为1的所有行(=所有组)。