推 pinkykk:推 02/13 09:32
※ 引述《cutekid (KID)》之銘言:
: 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: 111.255.9.99
使用 ORACLE Analytic Function 解法:
SELECT TYPE, MIN(ID) AS IDMIN, MAX(ID) AS IDMAX
FROM (
SELECT ID
, TYPE
, ID - ROW_NUMBER() OVER(PARTITION BY TYPE ORDER BY TYPE,ID ) RN
FROM TABLE1
)
GROUP BY TYPE, RN
ORDER BY MAX(ID);
謝謝。