一道挑战的SQL题目

lixj2009 2009-04-25 08:07:56
数据如下:
日期 事务所 标章NO.(varchar2)
12/12 北京 1
12/12 北京 2
12/12 北京 3
12/13 河北 51
12/13 河北 52
12/13 河北 53
12/13 河北 60
12/13 河北 70
输出结果如下: 只要日期和事务所一样,标章号连续就把记录合并
日期 事务所 标章NO.(varchar2)
12/12 北京 1-3
12/13 河北 51-53
12/13 河北 60
12/13 河北 70
...全文
116 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
hui1102 2011-08-20
  • 打赏
  • 举报
回复
select 日期,事务所,decode(a,b,a,b||'-'||a) 标章
from
(
select 日期,事务所,max(标章) a,min(标章) b
from

group by 日期,事务所,标章-rownum
)


结合前辈们的思想小弟改了一下
malili34 2009-04-26
  • 打赏
  • 举报
回复
我也学习下!
Megan2008 2009-04-26
  • 打赏
  • 举报
回复
select 日期,事务所,a||'-'||b
from (
select 日期,事务所,max(to_number(标章))a,min(to_number(标章))b
from table
group by 日期,事务所
)
where a<>b
union
select 日期,事务所,a
from (
select 日期,事务所,max(to_number(标章))a,min(to_number(标章))b
from table
group by 日期,事务所
)
where a=b
zhongxiutao123 2009-04-26
  • 打赏
  • 举报
回复
select
a.日期,a.事务所,to_char(a.标章NO)||(case when a.标章NO=min(b.标章NO) then '' else '-'||to_char(min(b.标章NO)) end) as 标章NO
from
(select t.* from 表名 t where not exists(select 1 from 表名 where 日期=t.日期 and 事务所=t.事务所 and 标章NO=t.标章NO-1)) a,
(select t.* from 表名 t where not exists(select 1 from 表名 where 日期=t.日期 and 事务所=t.事务所 and 标章NO=t.标章NO+1)) b
where
a.日期=b.日期 and a.事务所=b.事务所 and a.标章NO<=b.标章NO
group by
a.日期,a.事务所,a.标章NO
子陌红尘 2009-04-26
  • 打赏
  • 举报
回复
try:

select
a.日期,a.事务所,to_char(a.标章NO)||(case when a.标章NO=min(b.标章NO) then '' else '-'||to_char(min(b.标章NO)) end) as 标章NO
from
(select t.* from 表名 t where not exists(select 1 from 表名 where 日期=t.日期 and 事务所=t.事务所 and 标章NO=t.标章NO-1)) a,
(select t.* from 表名 t where not exists(select 1 from 表名 where 日期=t.日期 and 事务所=t.事务所 and 标章NO=t.标章NO+1)) b
where
a.日期=b.日期 and a.事务所=b.事务所 and a.标章NO<=b.标章NO
group by
a.日期,a.事务所,a.标章NO
lixj2009 2009-04-26
  • 打赏
  • 举报
回复
这道题,我用PL/SQL解决了。可是我不会用SQL语句来解决,哎,郁闷
求高手指点
cheng_fengming 2009-04-25
  • 打赏
  • 举报
回复
学习了 !
superhsj 2009-04-25
  • 打赏
  • 举报
回复
先mark了,回头接着看
superhsj 2009-04-25
  • 打赏
  • 举报
回复
哦,上面的不对
superhsj 2009-04-25
  • 打赏
  • 举报
回复
试试
select 日期,事务所,(to_number(标章NO.)-to_number(aa)) bb,min(标章NO.)||'-'||max(标章NO.)
from (select 日期,事务所,标章NO.,lag(标章NO.,1,9999) over (order by 日期,事务所,标章NO.) aa)
group by 日期,事务所,bb;

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧