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

2ramgopal gravatar image

2ramgopal
30 3 3 5

(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

Grant Fritchey gravatar image

Grant Fritchey ♦♦
101k 19 21 74

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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

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:

x109

asked: Aug 16, 2012 at 03:15 PM

Seen: 658 times

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