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.
Author |
Topic |
anishap
Yak Posting Veteran
61 Posts |
Posted - 2011-01-14 : 16:59:09
|
Can someone help me with the below query? Sample Patient TableID Name001 PAUL002 JOHN003 MARY004 JIM005 GEORGE006 JEAN007 SUZANNESample Vaccine tableID TYPE DUE-DATE001 Tetanus 09/01/2016001 TB 02/12/2011001 Hep B 03/04/2011002 TB 02/01/2011002 Tetanus 01/23/2013003 TB 02/14/2011004 TB 09/12/2011004 Tetatus 03/12/2019Sample OutputID Name DueDate001 PAUL 02/12/2011002 JOHN 02/01/2011003 MARY 02/14/2011 004 JIM 09/12/2011I tried the below querySELECT DISTINCT P.ID,P.NAME,V.DUEDATE from PATIENT E, VACCINE VWHERE E.ID = V.IDBut it is listing all rows. I just need the next duedate for each PATIENT.Please let me know |
|
dataguru1971
Master Smack Fu Yak Hacker
1464 Posts |
Posted - 2011-01-14 : 17:31:40
|
Something like this?Select ID, Name,b.NextDueDateFROM Patients inner join (SELECT ID,MIN([DUE-DATE]) as NextDueDate FROM Vaccine WHERE [Due-Date] > getdate()) bon Patients.ID = b.ID Poor planning on your part does not constitute an emergency on my part. |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-01-16 : 06:09:41
|
alsoSELECT ID, Name,NextDueDateFROM Patients pCROSS APPLY (SELECT TOP 1 DueDate FROM Vaccine WHERE ID = p.IDDUE-DATE AND DUE-DATE > GETDATE() ORDER BY DUE-DATE )v ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
Ranjit.ileni
Posting Yak Master
183 Posts |
Posted - 2011-01-18 : 02:02:55
|
create table #Patient(id int,name varchar(20))insert into #Patient(ID, Name)select 001 ,'pAUL' union allselect 002, 'JOHN'union allselect 003, 'MARY'union allselect 004, 'JIM' union allselect 005 ,'GEORGE' union allselect 006 ,'JEAN'union allselect 007 ,'SUZANNE'GOcreate table #Vaccine(id int,TYPE varchar(20),due date )insert into #Vaccineselect 001, 'Tetanus',' 09/01/2016'union allselect 001,' TB',' 02/12/2011'union allselect 001,' HepB',' 03/04/2011'union allselect 002,' TB ','02/01/2011'union allselect 002 ,'Tetanus',' 01/23/2013'union allselect 003,' TB ','02/14/2011'union allselect 004,' TB',' 09/12/2011'union allselect 004,' Tetatus',' 03/12/2019'GOselect p.id ,name ,CONVERT(VARCHAR(10), DueDate, 101)from #Patient p join (select ID ,MIN(due) as DueDate from #Vaccine group by id) v on p.ID = v.IDIRK |
 |
|
anishap
Yak Posting Veteran
61 Posts |
Posted - 2011-01-18 : 11:16:26
|
Thanks Ranjit, it worked. |
 |
|
|
|
|
|
|