SQL statements used to retrieve the first N records for DB2 Classification

Source: Internet
Author: User

The SQL statements described below are used to retrieve the first N records of the DB2 classification. If you have encountered the problem of retrieving the first N records of the DB2 classification, take a look.

There is a table t1 with the following structure:
Sort Category numbers
A aa 1
A aa2 4
A aa3 6
B bb 1
B bb2 3
B bb3 5
C cc 1
C cc2 5
C cc3 7
The results to be queried are the first two records of each category, sorted by order. The results are as follows:
Sort Category numbers
A aa 1
A aa2 4
B bb 1
B bb2 3
C cc 1
C cc2 5

Create table t1 (
YTypeCode varchar (10 ),
YMemo varchar (10 ),
YOrder int
)

Insert into t1 (yTypeCode, yMemo, yOrder) values ('A', 'A', 1 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('A', 'aa2 ', 4 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('A', 'aa3', 6 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('B', 'bb', 1 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('B', 'bb2', 2 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('B', 'bb3', 3 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('C', 'cc', 1 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('C', 'cc2', 5 );
Insert into t1 (yTypeCode, yMemo, yOrder) values ('C', 'cc3', 8)

Implementation;

SELECT * FROM t1 t
WHERE (SELECT count (*) FROM t1 WHERE yTypeCode = t. yTypeCode AND yOrder <t. yOrder) <2
 

Usage of DB2 Merge statements

Overview of DB2 Flow Control clauses

Principle of DB2 cursor

Two ways to store db2 logs

Common DB2 cycle usage

Related Article

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.