Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Typical requirement

Author  Topic 

satish.gorijala
Posting Yak Master

182 Posts

Posted - 2009-03-31 : 01:35:33
Hi, i have following data in table. Based on MZip Distance, i need to find out the CZIP Which is nearer to MZIP.

For Example, in the below data, the first row shows MZIP data 501 have distance '0'. Now i need to find out the CZIP which is nearest distance to '0'. Need to check all rows start with 501. Finally i will get result as 544 from CZIP.


MZIP CZIP DISTANCE
501 501 0
501 544 0
501 11742 0.32
501 11738 1.5
501 11741 1.66
605 605 0
605 603 2.58
605 604 4.16
605 602 5.47
611 611 0
611 685 2.14
611 670 3.37
611 669 6.71
613 613 0
613 614 0
613 616 5.6
613 659 6.61
613 612 6.84

The Final result is like this
MZIP CZIP Distance
501 544 0
605 603 2.58
611 685 2.14
613 614 0



G. Satish

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-03-31 : 02:48:01
[code]
declare @t table(MZIP int, CZIP int,DISTANCE decimal(18,2))
insert into @t select 501, 501, 0
insert into @t select 501, 544, 0
insert into @t select 501, 11742, 0.32
insert into @t select 501, 11738, 1.5
insert into @t select 501, 11741, 1.66
insert into @t select 605, 605, 0
insert into @t select 605, 603, 2.58
insert into @t select 605, 604, 4.16
insert into @t select 605, 602, 5.47
insert into @t select 611, 611, 0
insert into @t select 611, 685, 2.14
insert into @t select 611, 670, 3.37
insert into @t select 611, 669, 6.71
insert into @t select 613, 613, 0
insert into @t select 613, 614, 0
insert into @t select 613, 616, 5.6
insert into @t select 613, 659, 6.61
insert into @t select 613, 612, 6.84

select MZIP , CZIP ,DISTANCE from (select row_number()over(partition by mzip order by mzip) as rid , * from @t) s
where rid = 2
[/code]
Go to Top of Page
   

- Advertisement -