I have two tables of names and names as shown below.
Platform: SQL Server 2005/2008.
Names table: Nam ID
and
name_ids table ID ----------- 3 6 8
I would like to create the following output connecting these tables.
Nam Nam_ID ID -------------------------------- ----------- ----------- A 1 NULL B 2 NULL C 3 3 D 4 3 E 5 3 F 6 6 G 7 6 H 8 8
The logic matches the identifier nam_id and if nam_id is less than any id then return NULL. If nam_id is greater than or equal to id, then return id. Here is the catch. In the above example, for F, 6, we should not return a combination of F, 6,3, but we should only return a match of F, 6,6. when the matching element is found as 6.6, it should skip other matches, such as 6.3. After that, use 7.6, not 7.3. How to write a sql query for the above? The request is time consuming and requires fast execution.
Scripts: Create table Names(Nam nvarchar(32), ID int); insert into names values('A', 1); insert into names values('B', 2); insert into names values('C', 3); insert into names values('D', 4); insert into names values('E', 5); insert into names values('F', 6); insert into names values('G', 7); insert into names values('H', 8); Create table name_ids( ID int); insert into name_ids values(3); insert into name_ids values(6); insert into name_ids values(8);
Please, help.
Update: Hey guys, really appreciate your efforts to provide solutions. Now I'm confused to choose the most effective query. I took a few and tried to analyze performance with very large result sets.