|
|
Question : SQL statement for displaying one record each out of multiple records
|
|
Hi. I'm in need of an expert who can give me an idea on how to select the first instance record out the multiple records. See an example of a resultset below. The SQL has a join statement for 2 tables (Name, Phone)
ID ID_Seq ID_Name PhoneID PhoneSeq PhoneNo a 1 Mine a1 1 123 a 1 Me a1 2 234 b 2 Yours a2 1 111 c 3 a3 2 222 c 3 a3 3 456
I would like to get one of each, see below, to be displayed on a listbox for the UI. (Please note that not all ID_Seq & PhoneSeq stars with '1')
ID ID_Seq ID_Name PhoneID PhoneSeq PhoneNo a 1 Mine a1 1 123 b 2 Yours a2 1 111 c 3 a3 2 222
|
Answer : SQL statement for displaying one record each out of multiple records
|
|
O.K. now it makes more sense.
The actual problem is you have to pick one Phone record out of the pile for each Employee and, as far as you have told us, it doesn't matter which one.
If you were using ASE 15.0.2, we could utilize one of the OLAP extensions to SQL to grab the record you want but in this case, we are going to have to do it the hard way.
I outlined the technique below. It uses a trick with the Group By and Having clauses in a Derived table.
create table employee (col1 int, col2 int) go create table phone (col1 int, col3 int, col4 varchar(32)) go
insert into employee values (1,1) insert into employee values (2,2) insert into employee values (3,3) go
insert into phone values (1,1,'123-456-7890') insert into phone values (1,2,'223-456-7890') insert into phone values (2,1,'323-456-7890') insert into phone values (3,2,'423-456-7890') insert into phone values (3,3,'523-456-7890') go
select e.*, p.* from employee e join (select col1, col3, col4 from phone group by col1 having min(col3) = col3) p on p.col1 = e.col1 go
Regards, Bill
|
|
|
|
|