首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于动物数据集中的范围的列- sql

基于动物数据集中的范围的列- sql
EN

Stack Overflow用户
提问于 2020-08-18 17:22:25
回答 2查看 77关注 0票数 0

表:

代码语言:javascript
复制
num       value      category      name
503       8978       bird          woodpecker
502       7812       animal        
502       7812       animal        
501       7812       animal        
500       7812       animal        panther
499       7812       animal        
498       7812       animal     
467       7812       animal        elephant           

partition byvaluecategory列中,应该创建输出列,如下所示:

name不是null时,output列将占用name的值,并在+2和减去两个num列的范围内填充相同的值。

例如,500有name not null,500-2=498,500+2=502,在498到502的范围内,输出用panther填充。

输出:

代码语言:javascript
复制
  num       value      category      name             output
  503       8978       bird          woodpecker       
  502       7812       animal                         panther
  502       7812       animal                         panther
  501       7812       animal                         panther
  500       7812       animal        panther          panther
  499       7812       animal                         panther
  498       7812       animal                         panther
  467       7812       animal        elephant         elephant 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-18 18:30:11

您可以使用range窗口框架:

代码语言:javascript
复制
select t.*,
       coalesce(name,
                max(name) over (partition by category
                                order by num
                                range between 2 preceding and 2 following
                               )
               ) as imputed_name
from t;

这里是db<>fiddle。

编辑:

对于Postgres中的range窗口框架来说,对“前面”和“跟随”的支持是相对较新的。在旧版本中,横向连接可能是最简单的方法:

代码语言:javascript
复制
select t.*,
       coalesce(t.name, t2.name) as imputed_name
from t left join lateral
     (select t2.name
      from t t2
      where t2.category = t.category and
            t2.name is not null and
            t2.num between t.num - 2 and t.num + 2
      limit 1
     ) t2
     on 1=1
order by num desc;

这里是这个版本的db<>fiddle。

票数 1
EN

Stack Overflow用户

发布于 2020-08-18 17:33:20

尝试在大小写中使用窗口函数:

代码语言:javascript
复制
select num,value,category,name,output from
(
--if num is in range [match_number-2, match_number+2] then get animal's name
select *, CASE when num>=(match_number-2) and num<=(match_number+2) then max_nam else NULL end as output from
 (
 --find num matching name
 select *,max( case when name=max_nam then num else 0 end )over (partition by value,category) match_number from
  (
  --find name (not null) partition by value,category 
   select *,max(name)over(partition by value,category)max_nam from Table
  )X
 )Y
)Z
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63473650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档