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 2000 Forums
 SQL Server Development (2000)
 join two table by sequence

Author  Topic 

cjcclee
Starting Member

33 Posts

Posted - 2006-09-29 : 09:34:30
My original post is here:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=72651

khtan help me to get result. Basically, it generate RowID for each patient. It works. Thanks so much! But in my case, tabel A is generated by user when they select Criteria, so not all patient's each admission and discharge corresponding each applicationtime is in table A.
for example

table a
ssn applicationtime
1234 1/1/2005
1234 1/1/2006

table b
ssn Admissiontime Dischargetime
1234 1/8/2005 2/10/2005
1234 1/1/2006 2/10/2006


when user select criteria such as date, patient's doctor...
table a
ssn applicationtime
1234 1/1/2006

if I use order of RowID join, the result will be
1234 1/1/2006 1/8/2005 2/10/2005

which is not correct.

I do not have column can realted table A and table B besides ssn.
criteria used on table a can not apply on table B.

I think join condition should be ssn and Min(DateDiff(day, applicationtime,admissiontime))

How can I wrote this query? Thanks!!

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-09-30 : 02:46:11
Hi ! It's me again to give it another try

declare @tablea table
(
ssn int,
applicationtime datetime
)

declare @tableb table
(
ssn int,
admissiontime datetime,
dischargetime datetime
)
insert into @tablea
select 1234, '1/1/2005' union all
select 1234, '2/1/2006'

insert into @tableb
select 1234, '1/9/2005', '1/23/2005' union all
select 1234, '2/7/2006', '3/31/2006'

select a.ssn, a.applicationtime, b.admissiontime, b.dischargetime
from @tablea a inner join @tableb b
on a.ssn = b.ssn
and a.applicationtime <= b.admissiontime
and b.admissiontime = (select top 1 y.admissiontime
from @tablea x inner join @tableb y
on x.ssn = y.ssn
and x.applicationtime = a.applicationtime
and x.applicationtime <= y.admissiontime
order by datediff(day, x.applicationtime, y.admissiontime)
)

/* RESULT
ssn applicationtime admissiontime dischargetime
----------- ------------------------ ------------------------- -----------------------
1234 2005-01-01 00:00:00.000 2005-01-09 00:00:00.000 2005-01-23 00:00:00.000
1234 2006-02-01 00:00:00.000 2006-02-07 00:00:00.000 2006-03-31 00:00:00.000

(2 row(s) affected)
*/



KH

Go to Top of Page

cjcclee
Starting Member

33 Posts

Posted - 2006-10-02 : 15:54:52
khtan,Thanks so much! I am very apprectaied your help.
It works! I think it is best way to solve the problem.
Thanks again!
Go to Top of Page
   

- Advertisement -