It is very practical to use SQL to query consecutive code segments. (This is often used by the billing system or sp)

Source: Internet
Author: User
Tags how to use sql

It is very practical to use SQL to query consecutive code segments. (This is often used by the billing system or sp)

How to use SQL to query consecutive code segments in a database
There is a clever SQL technique on [database]. Learn it and record it here.

The initial problem was as follows:

I have a table structure,
Fphm, kshm
Int32 00000001
Int32 00000002
Int32 00000003
Int32 00000004
Int32 00000005
Int32 00000007
Int32 00000008
Int32 00000009
Maid
Maid
Maid
Maid
Maid

(The second field may contain continuous data and may contain breakpoints .)

How can we query such results and query continuous records.
As shown below?
Int32 00000001, 00000005
00000007
Maid, 00000122
00000125

Database:

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

The clever thinking is in the process of thinking.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.