作者cutekid (KID)
看板Database
标题Re: [SQL ] 请问查询资料区间的语法
时间Sat Feb 2 02:03:11 2013
select a.type,a.idmin,min(b.idmax)
from (
select type,id as idmin
from table t1
where not exists(
select id
from table t2
where t2.id = t1.id - 1 and t2.type = t1.type
)
) a,(
select type,id as idmax
from table t3
where not exists(
select id
from table t4
where t4.id = t3.id +1 and t4.type = t3.type
)
) b
where a.type = b.type and a.idmin <= b.idmax
group by a.type,a.idmin
※ 引述《cherman (penguin)》之铭言:
: 请问我有一个资料表
: ID TYPE
: ==================
: 1 A
: 2 A
: 3 B
: 4 B
: 5 A
: 6 C
: 希望查询的结果是:
: TYPE IDMIN IDMAX
: =====================
: A 1 2
: B 3 4
: A 5 5
: C 6 6
: 我的语法应该怎麽下才有上列结果?谢谢!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 36.225.168.230
1F:推 jojobill:这样的写subquery,DB会跑的唉唉叫 02/03 14:15
2F:→ cutekid:哈哈 ^_^ 02/03 16:45
3F:→ bobju: 拐拐叫 02/03 19:50
4F:→ jojobill:身为DBA写出这种query的developer都想跟他好好谈谈… 02/03 19:59
5F:→ cutekid:(逃) 02/03 20:22
6F:推 cherman:CUTE大太厉害了,感恩… 02/05 10:25