在itpub上有一則非常巧妙的
sql技巧,學習一下,記錄在這裡。
最初的問題是這樣的:
itpub上的朋友給出了乙個非常巧妙的答案:我有乙個表結構,
fphm,kshm
2014,00000001
2014,00000002
2014,00000003
2014,00000004
2014,00000005
2014,00000007
2014,00000008
2014,00000009
2013,00000120
2013,00000121
2013,00000122
2013,00000124
2013,00000125
(第二個欄位內可能是連續的資料,可能存在斷點。)
怎樣能查詢出來這樣的結果,查詢出連續的記錄來。
就像下面的這樣?
2014,00000001,00000005
2014,00000009,00000007
2013,00000120,00000122
2013,00000124,00000125
sql> select b.fphm, min (b.kshm) start_hm, max (b.kshm) end_hm巧思妙想,就在一念之間。2 from (select a.*, to_number (a.kshm - rownum) cc
3 from (select *
4 from t
5 order by fphm, kshm) a) b
6 group by b.fphm, b.cc
7 /fphm start_hm end_hm
---------- -------- --------
2013 00000120 00000122
2013 00000124 00000125
2014 00000001 00000005
2014 00000007 00000009
create table t(fphm varchar2(4),kshm varchar2(8))
insert into t(fphm,kshm)
values(2014,'00000001');
insert into t(fphm,kshm)
values(2014,'00000002');
insert into t(fphm,kshm)
values(2014,'00000003');
insert into t(fphm,kshm)
values(2014,'00000004');
insert into t(fphm,kshm)
values(2014,'00000005');
insert into t(fphm,kshm)
values(2014,'00000007');
insert into t(fphm,kshm)
values(2014,'00000008');
insert into t(fphm,kshm)
values(2014,'00000009');
insert into t(fphm,kshm)
values(2013,'00000120');
insert into t(fphm,kshm)
values(2013,'00000121');
insert into t(fphm,kshm)
values(2013,'00000122');
insert into t(fphm,kshm)
values(2013,'00000124');
insert into t(fphm,kshm)
values(2013,'00000125');
select b.fphm, min (b.kshm) start_hm, max (b.kshm) end_hm
from (select a.*, to_number (a.kshm - rownum) cc
from (select *
from t
order by fphm, kshm) a) b
group by b.fphm, b.cc
如何查詢出連續日期記錄
截圖如下 insus.net嘗試寫了程式並做了測試,可以得到預期的結果,sql 可參考和學習之用。建立乙個臨時表,將會儲存連續日期的記錄 create table temp idd varchar 10 sdate datetime declare sddatetime 開始日期 declare e...
如何查詢出資料庫中不存在的記錄
這兩天經常遇到一道題,即如何用一條語句在資料庫中查詢出不存在的記錄.注意,是一條語句哦.一般情況下,該題有個前提條件,必定有乙個欄位是按規律生成的,如小時記錄,一天24條記錄.或者是按照序號生成,如12345678等.我的思路是構造乙個偽表,然後用偽表進行關聯查詢.create table test...
MySql高效的查詢出隨機記錄的方法
select from t code game where id select max id from t code game select min id from t code game rand select min id from t code game limit 1 通過i最小與最大的自增...