【问题标题】:How to get final length of a line in a query?如何获取查询中一行的最终长度?
【发布时间】:2021-03-20 16:26:24
【问题描述】:

我刚刚学习 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 

这真的只给了我所有并非完全无用的行并延长了长度,但我不知道从这里做什么。

【问题讨论】:

    标签: sqlite with-statement


    【解决方案1】:

    使用递归 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

    【讨论】:

    • 谢谢你,我没想到那样做递归。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2021-06-18
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多