【问题标题】:Gaps and islands SQL error间隙和孤岛 SQL 错误
【发布时间】:2014-12-17 19:38:51
【问题描述】:

尝试运行查询以识别表中间隙和孤岛的开始和停止。我正在应用一个我认为适用于我的数据集的查询,但我无法正常运行。运行此代码时出现转换错误:

select start, stop 
from (
select m.API_WellNo + 1 as start,
    (select min(API_WellNo) - 1 
    from tblWellMaster x 
    where x.API_WellNo > m.API_WellNo) as stop
from tblWellMaster m    left outer join tblWellMaster r on m.API_WellNo = r.API_WellNo - 1
where r.API_WellNo is null
  ) as x
where stop is not null;

这是我得到的错误: nvarchar 值 '31003022850000' 的转换溢出了一个 int 列。

我不知道这个 int 列是从哪里来的,因为我的 API_WellNo 是一个 nvarchar(14)

数字是组成我试图找到间隙/岛屿的序列之一,非常感谢任何帮助,谢谢

【问题讨论】:

  • 我认为 min 正在将 API_WellNo 从 nvarchar 转换为 int。列出的数字对于 int 列来说太大了。
  • m.API_WellNo + 1min(API_WellNo) - 1 导致隐式转换为数字类型
  • 也许做个转换MIN(CAST(API_WellNo AS BIGINT))
  • 您使用的是什么数据库?这个问题可能有更有效的解决方案。

标签: sql sql-server integer-overflow gaps-and-islands


【解决方案1】:

试试这个:

with cte as (
  select start = (cast(m.API_WellNo as bigint) + 1)
      , [stop] = ca.[stop]
    from tblWellMaster m    
      cross apply (
        select top 1 [stop]=(cast(x.API_WellNo as bigint) -1)
          from tblWellMaster x 
          where x.API_WellNo > m.API_WellNo
          order by x.API_WellNo
        ) as ca
    where not exists (
      select 1 
        from tblWellMaster r 
        where cast(m.API_WellNo as bigint)  = (cast(r.API_WellNo as bigint)  - 1))
  )
  select start, [stop] 
    from cte 
    where [stop] is not null;

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 2018-12-05
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多