gpt4 book ai didi

sql-server - 如何在SQL中的组内按顺序查找缺失值?

转载 作者:行者123 更新时间:2023-12-04 18:22:01 26 4
gpt4 key购买 nike

我有一个 ID 和位置表

CREATE TABLE #MissingSequence (ID INT NOT NULL, Position INT NOT NULL)
INSERT INTO #MissingSequence (ID,Position)
SELECT 36,1
UNION ALL SELECT 36,2
UNION ALL SELECT 36,3
UNION ALL SELECT 36,4
UNION ALL SELECT 36,5
UNION ALL SELECT 36,6
UNION ALL SELECT 44,1
UNION ALL SELECT 44,3
UNION ALL SELECT 44,4
UNION ALL SELECT 44,5
UNION ALL SELECT 44,6

我要查找的是,在这种情况下,44,1 和 44,3 之间的 ID 位置序列中是否有任何中断

我已经设法一起解析:

SELECT  l.ID
,Start_Position = MIN(l.Position) + 1
,Stop_Position = MIN(fr.Position) - 1
FROM #MissingSequence l
LEFT JOIN #MissingSequence r
ON l.Position = r.Position - 1
LEFT JOIN #MissingSequence fr
ON l.Position < fr.Position
WHERE r.Position IS NULL
AND fr.Position IS NOT NULL
GROUP BY l.ID

但如果有多个 ID 值,它就不起作用。如果只有一个 ID,44 存在,它确实有效。

想法、意见、建议?

谢谢!

最佳答案

左自联接是一种很好的直觉,但我认为聚合不会削减它,当然您需要在自联接中包含匹配 ID 子句。

这是一个使用 null-left-join 思想的(符合 ANSI 标准的)版本,选择顶行和底行并检查它们之间没有任何内容:

SELECT
above.ID AS ID, below.Position+1 AS Start_Position, above.Position-1 AS End_Position
FROM MissingSequence AS above
JOIN MissingSequence AS below
ON below.ID=above.ID AND below.Position<above.Position-1
LEFT JOIN MissingSequence AS inbetween
ON inbetween.ID=below.ID AND inbetween.Position BETWEEN below.Position+1 AND above.Position-1
WHERE inbetween.ID IS NULL;

+----+----------------+--------------+
| ID | Start_Position | End_Position |
+----+----------------+--------------+
| 44 | 2 | 2 |
+----+----------------+--------------+

关于sql-server - 如何在SQL中的组内按顺序查找缺失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/727392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com