如何获取查询中一行的最终长度?
How to get final length of a line in a query?
我刚刚在学习 SQL,我接到了一个任务,当我输入时,我需要找到不连续线的最终长度,例如:
start | finish
0 | 3
2 | 7
15 | 17
这里的正确答案是 9,因为它跨越 0-3,然后我被支持忽略多次出现的部分,所以从 3-7(忽略两者,因为它介于 0 和3 已经)和 15-17。我应该仅通过 sql 查询(无函数)获得此答案,但我不确定如何获得。我曾尝试使用 with 来试验一些代码,但我终其一生都无法弄清楚如何正确地忽略所有倍数。
我的半尝试:
WITH temp AS(
SELECT s as l, f as r FROM lines LIMIT 1),
cte as(
select s, f from lines where s < (select l from temp) or f > (select r from temp)
)
select * from cte
这实际上只给了我所有的行,这些行并没有完全无用并延长了长度,但我不知道从这里可以做什么。
使用递归 CTE
将所有 (start, finish)
间隔分解为与间隔总长度一样多的 1 个单位 长度间隔,然后计算所有不同的间隔:
WITH cte AS (
SELECT start x1, start + 1 x2, finish FROM temp
WHERE start < finish -- you can omit this if start < finish is always true
UNION
SELECT x2, x2 + 1, finish FROM cte
WHERE x2 + 1 <= finish
)
SELECT COUNT(DISTINCT x1) length
FROM cte
参见demo。
结果:
length
9
我刚刚在学习 SQL,我接到了一个任务,当我输入时,我需要找到不连续线的最终长度,例如:
start | finish
0 | 3
2 | 7
15 | 17
这里的正确答案是 9,因为它跨越 0-3,然后我被支持忽略多次出现的部分,所以从 3-7(忽略两者,因为它介于 0 和3 已经)和 15-17。我应该仅通过 sql 查询(无函数)获得此答案,但我不确定如何获得。我曾尝试使用 with 来试验一些代码,但我终其一生都无法弄清楚如何正确地忽略所有倍数。 我的半尝试:
WITH temp AS(
SELECT s as l, f as r FROM lines LIMIT 1),
cte as(
select s, f from lines where s < (select l from temp) or f > (select r from temp)
)
select * from cte
这实际上只给了我所有的行,这些行并没有完全无用并延长了长度,但我不知道从这里可以做什么。
使用递归 CTE
将所有 (start, finish)
间隔分解为与间隔总长度一样多的 1 个单位 长度间隔,然后计算所有不同的间隔:
WITH cte AS (
SELECT start x1, start + 1 x2, finish FROM temp
WHERE start < finish -- you can omit this if start < finish is always true
UNION
SELECT x2, x2 + 1, finish FROM cte
WHERE x2 + 1 <= finish
)
SELECT COUNT(DISTINCT x1) length
FROM cte
参见demo。
结果:
length |
---|
9 |