简体   繁体   中英

How to get min & max date across the database for each subject

I have a psotgresql db which has 4 tables and each table has a date column.

Table 1

person_id       meas_date

  1            2007/02/11
  2            2008/05/13  
  3            2008/07/29
  5            2006/03/21

Table 2

person_id     visit_date

  1            2003/06/21
  2            2005/02/23  
  3            2006/04/19
  5            2004/06/11

Table 3

person_id     condition_date

  1            2008/06/21
  2            2009/02/23  
  3            2005/04/19
  5            2002/06/11

Table 4

person_id       d_date

  1            2018/06/21
  2            2005/02/23  
  3            2004/04/19
  5            2009/06/11

Currently I do something like below to find it from one table but how do I find across all the tables in my db. In this case, it is 4 tables

select 
  person_id,
  min(condition_start_date) as min_date,
  max(condition_start_date) as max_data,
from Table_3
group by person_id

But can you please help me find across the all tables for a subject/person_id?

I expect my output to be like below

person_id       max_date      min_date

  1            2018/06/21    2003/06/21
  2            2009/02/23    2005/02/23
  3            2006/04/19    2004/04/19
  5            2009/06/11    2002/06/11

Use union all and aggregation:

select person_id, min(date), max(date)
from ((select person_id, date from table1) union all
      (select person_id, date from table2) union all
      (select person_id, date from table3) union all
      (select person_id, date from table4) 
     ) pd
group by person_id;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM