x

How to select rows from a table from other table key column value +1

Hi,

I just went through a situation where there are 2 tables and I need a select rows from first table based on the key column of second table incremented by 1. For example:

Table1:

1 hari 123

2 hari2 321

3 hari3 432

4 hari4 234

5 hari5 543

Table2:

1 hari 123

4 hari4 234

The result selection must display 2 and 5 i.e..

2 hari2 321

5 hari5 543

Please share your answers.

Thanks, Ram

more ▼

asked Aug 16, 2012 at 03:15 PM in Default

avatar image

2ramgopal
30 3 3 7

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

You can just put that right into the JOIN criteria:

 SELECT * 
 FROM dbo.Table1 AS t1
 JOIN dbo.Table2 AS t2
 ON t1.ID +1 = t2.ID;

Now, that does act as a function on the column, so it may result in scans. Test it to be sure.

more ▼

answered Aug 16, 2012 at 03:24 PM

avatar image

Grant Fritchey ♦♦
137k 20 43 81

Thanks for your response Fritchey.

My expectation is it should pick 1 nd 4 key values from table 1 and display 2 and 5 from first table.

Aug 16, 2012 at 03:51 PM 2ramgopal

It worked. Did some minor changes based on my data and got it.Thanks Fritchey.

Aug 16, 2012 at 06:24 PM 2ramgopal
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x148

asked: Aug 16, 2012 at 03:15 PM

Seen: 786 times

Last Updated: Aug 16, 2012 at 06:26 PM

Copyright 2016 Redgate Software. Privacy Policy