简体   繁体   中英

including limit to select top n rows within a group by clause

I have the following 2 tables:

create table1
(
   SENDER int,
   RECEIVER int,
   TIME time,
   TYPE char(1)
);

create table2
(
   ID int,
   Y int,
   CONTACT int,
   DATE time
);

I am executing the following join query:

SELECT B.ID, A.RECEIVER AS Z, A.SENDER AS CONTACT, A.TYPE, A.TIME
FROM table1 A 
JOIN table2 B ON A.RECEIVER = B.CONTACT 
WHERE A.TYPE = 'A'
   AND A.TIME < B.DATE

How do I modify the query to return only the top 40 results for each (ID,CONTACT) pair using GROUP BY ?

I can order the data using the field table2.DATE

since i wanted top 40 results for each ID, i made ID,autoId as a primary key, here autoId is an autoincrement key. so after executing the following query: SELECT B.ID, A.RECEIVER AS Z, A.SENDER AS CONTACT, A.TYPE, A.TIME FROM table1 A JOIN table2 B ON A.RECEIVER = B.CONTACT WHERE A.TYPE = 'A' AND A.TIME < B.DATE i get results such that, the autoId initializes to 1 for each ID for eg:

ID CONTACT autoId
1 2 1
1 3 2
1 11 3
1 34 4
2 5 1
2 33 2
2 56 3

since autoId is autoincrement, there is already an index on it. after this table is created, i can easily delete the results where autoId is greater than 40. and this while process runs really fast!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM