How to Compare Rows in SQL?

SQL query retrieving first two rows.?

  • I have two tables company and contacts in SQL. A company has c_id as primary key which is a foreign key in contacts. How can i design a query by which i can retrieve the first two contacts of every company in SQL?

  • Answer:

Serge M at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Most databases have a way to do something like this, but it's not very standardized. For instance, in MySQL, to get the first two contacts for company #17, you'd do something like: SELECT * FROM `contacts` WHERE `c_id` = 17 LIMIT 0, 2 But in DB2 it'd be: SELECT * FROM CONTACTS WHERE C_ID = 17 FETCH FIRST 2 ROWS ONLY

Silent

select c_id "company_id" , ( select contactid from contacts where contacts.c_id = company.c_id and rownum < 2) "First contact Id", ( select contactid from contacts where contacts.c_id = company.c_id and rownum < 3 and contactid != (select contactid from contacts where contacts.c_id = company.c_id and rownum < 2) ) "Second Contact Id" from company ; the above inner query logic will help you

ananthnag

easy. do a loop command and terminate after the second read of contacts.

Mars

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.