BH1234


Please help, I want to do a select query selecting the ID (from table 1) for where the person is under 18 and if there has been an episode (table 2) done on the person in the last 12 months (ie. Start date). The problem I¡¯m having is that there may be more than one episode that has been done. I think I need a query something like this

Select t1.id from table1 t1

Where

Exists(select * from table2 t2

Where t2.start_date> dateadd(m,-12,getdate())

And

T1.dob>getdate()

Table 1

People DOB

ID

100 23/2/1980

101 12/12/1968

102 1/1/2000

103 12/12/2003

Table 2

Episode People Start_Date

45 100 30/01/2003

46 100 12/01/2007

47 101 01/01/2002

48 103 19/2/2007

Result

People ID

100

103




Re: Stuck on a Inner Query

Manivannan.D.Sekaran


here it is.. Modified..

SET DATEFORMAT DMY

Create Table #person (

[PeopleId] int ,

[DOB] datetime

);

Insert Into #person Values('100','23/2/1990');

Insert Into #person Values('101','12/12/1968');

Insert Into #person Values('102','1/1/2000');

Insert Into #person Values('103','12/12/2003');

Create Table #episode (

[Episode] int ,

[People] int ,

[Start_Date] datetime

);

Insert Into #episode Values('45','100','30/01/2003');

Insert Into #episode Values('46','100','12/01/2007');

Insert Into #episode Values('47','101','01/01/2002');

Insert Into #episode Values('48','103','19/2/2007');

Select * from #Person Where DateAdd(YY,18,Dob) > getdate()

And Exists (Select 1 from #episode Where

DateAdd(MM,12,Start_Date) > Getdate()

And [PeopleId] = People

)







Re: Stuck on a Inner Query

DaleJ

Here ya go:

Code Snippet

SET DATEFORMAT DMY

create table #People (ID int, DOB datetime)

insert into #People

SELECT 100, '23/2/1999'

UNION ALL SELECT 101, '12/12/1968'

UNION ALL SELECT 102, '1/1/2000'

UNION ALL SELECT 103, '12/12/2003'

UNION ALL SELECT 104, '14/2/1970'

create table #Episode(EpisodeID int, PeopleID int, Start_Date datetime)

insert into #Episode

SELECT 45, 100, '30/01/2003'

UNION ALL SELECT 46, 100, '12/01/2007'

UNION ALL SELECT 47, 101, '01/01/2002'

UNION ALL SELECT 48, 103, '19/2/2007'

UNION ALL SELECT 49, 104, '25/12/2005'

SELECT ID

FROM #People p

WHERE DOB >= convert(datetime, convert(varchar(10), dateadd(yy, -18, getdate()), 103))

AND EXISTS

(

SELECT *

FROM #Episode e

WHERE p.ID = e.PeopleID

AND Start_date >= convert(datetime, convert(varchar(10), dateadd(mm, -12, getdate()), 103))

)







Re: Stuck on a Inner Query

richbrownesq

Guys- i notice you're using DATEDIFF(YY,DOB,GETDATE()) < 18.


Doesn't this just do the difference in the year dateparts of a date To actually do ages, i think you'd need to do something along the lines of:

dob > dateadd(yy, -18, convert(varchar,getdate())

Make sense







Re: Stuck on a Inner Query

DaleJ

Correct Rich.

DOB calc's have to take month/day into consideration to get a proper value.