LEAD/LAG SQL 服务器 2012/差距和岛屿

LEAD/LAG SQL Server 2012/Gaps and Islands

我在使用 LEAD/LAG 时遇到了一些问题。对于一组 ID 中的每一行,我想要获取 previous/next 来源,其中 isAQI = 1。所需的输出在 prevAQI 和 nextAQI 列中如下所示。

我尝试了与 Lag() with conditon in sql server 相同的方法,但没有成功。任何帮助将不胜感激!

示例数据如下:

DECLARE @a TABLE ( id int, timest datetime, source char(2),
                   isAQI int, prevAQI char(2), nextAQI char(2))
INSERT @a VALUES
(6694   ,'2015-06-11 08:55:06.000'  ,'I'    ,1, NULL, 'A'), 
(6694   ,'2015-06-11 09:00:00.000'  ,'A'    ,1, 'I', 'I'),
(6694   ,'2015-06-11 09:11:49.000'  ,'C'    ,NULL, 'A', 'I'),
(6694   ,'2015-06-11 09:29:06.000'  ,'O'    ,NULL, 'A', 'I'),
(6694   ,'2015-06-11 09:29:06.000'  ,'DT'   ,NULL, 'A', 'I'),
(6694   ,'2015-06-11 09:34:11.000'  ,'DT'   ,NULL, 'A', 'I'),
(6694   ,'2015-06-11 09:34:11.000'  ,'O'    ,NULL, 'A', 'I'),
(6694   ,'2015-06-11 10:06:27.000'  ,'I'    ,1, 'A', 'I'),
(6694   ,'2015-06-11 11:25:09.000'  ,'DT'   ,NULL, 'I', 'I'),
(6694   ,'2015-06-11 18:25:24.000'  ,'C'    ,NULL, 'I', 'I'),
(6694   ,'2015-06-12 17:57:16.000'  ,'I'    ,1, 'I', NULL);

SELECT *
FROM @a  

查看以下查询是否适合您:

WITH C AS
(
  SELECT *,
    MAX(goodval) OVER(PARTITION BY id
                      ORDER BY timest
                      ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS prv,
    MIN(goodval) OVER(PARTITION BY id
                      ORDER BY timest
                      ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) AS nxt
  FROM @a
    CROSS APPLY ( VALUES( CONVERT(VARCHAR(23), timest, 121) 
                          + CASE WHEN isAQI = 1 THEN source END ) ) AS A(goodval)
)
SELECT id, timest, source,
CASE WHEN prv IS NOT NULL THEN SUBSTRING(prv, 24, 2) END AS prevAQI,
CASE WHEN nxt IS NOT NULL THEN SUBSTRING(nxt, 24, 2) END AS nextAQI
FROM C
ORDER BY id, timest;