Please forgive me if this is a basic question, I'm a beginner in SQL and need some help performing date calculations from 2 tables in SQL.
I have two tables (patient and chd) they look like this:
Patient :
ID|Age|date |Alive
--------------------------
1 50 01/09/2013 Y
2 52 11/05/2015 N
3 19 20/07/2016 N
CHD :
ID|Age|indexdate
--------------------
1 50 01/08/2012
2 52 11/11/2013
3 19 10/07/2015
The patient table contains about 500,000 records from 2010-2016 and the CHD table contains about 350,000 records from 2012-2013. What I want to do is see how many CHD patients have died from 2012-2016, and if they have died has 12months passed?
I'm not sure how to do this but I know a join is needed on the ID and we set the where condition with alive as NOT 'Y'
The final output should look like this based on the sample above:
ID|Age|indexdate| deathdate
---------------------------
2 52 11/11/2013 11/05/2015
3 19 10/07/2016 20/07/2016
Any questions let me know!
EDIT: just to make it clear, patients can appear multiple times in the patient table until they die.
Thanks
Let me assume that this query gets the date of death from the patient
table:
select p.id, min(p.date) as deathdate
from patient p
where p.Alive = 'N'
group by p.id;
Then, you can get what you want with a join:
select count(*)
from chd c join
(select p.id, min(p.date) as deathdate
from patient p
where p.Alive = 'N'
group by p.id
) pd
on c.id = pd.id;
You can then address your questions with a where
clause in the outer query. For instance:
where deathdate >= current_date - interval '1 year'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.