You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL查询结果合并为一行,获取MIN(KNANF)与MAX(KNEND)?

问题描述

我有一张TVRAB表,数据如下:

routeabnumknanfknend
000121PISY
000122SYPA
000123PAHN

当前执行如下SQL查询:

select knanf as start, knend as end 
from TVRAB as a 
where route = '00012' 
and ( abnum = ( select min( ABNUM ) from TVRAB where route = a~route ) 
      or abnum = ( select max( ABNUM ) from TVRAB where route = a~route ) )

得到两行结果:

STARTEND
PISY
PAHN

需要将指定route对应的最小abnum对应的knanf和最大abnum对应的knend合并为一行输出,期望结果如下:

STARTEND
PIHN
解决方案

可以通过两种方式实现单行输出:

方法1:聚合查询结合子查询

select 
    (select knanf from TVRAB where route = '00012' and abnum = min(abnum)) as START,
    (select knend from TVRAB where route = '00012' and abnum = max(abnum)) as END
from TVRAB
where route = '00012'
group by route;

方法2:窗口函数(支持窗口函数的数据库适用)

select distinct
    first_value(knanf) over (partition by route order by abnum) as START,
    last_value(knend) over (partition by route order by abnum rows between current row and unbounded following) as END
from TVRAB
where route = '00012';

说明

  • 方法1通过分组后,分别子查询获取最小abnum对应的起点、最大abnum对应的终点,直接返回单行结果。
  • 方法2利用first_value和last_value窗口函数,在分组内按abnum排序后取第一个knanf和最后一个knend,通过distinct去重得到单行结果。

内容的提问来源于stack exchange,提问作者ekekakos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 11:01:03