Master_table Table_A
ID Problem Date ID Problem Date
101 123 01-02-1993 101 123 01-02-1993
101 124 101 124
102 125 102 125 07-02-1994
103 126 08-22-1999 103 126 08-22-1999
103 131 103 131 08-09-1999
Table_B Table_C
ID Problem Date ID Problem Date
101 124 101 124
102 125 06-30-1994 102 125
103 126 08-22-1999 103 131 08-08-1999
103 131 08-09-1999 106 137 02-02-1987
106 137 01-02-1987 110 145 12-22-1995
我需要创建一个名为'final_table'的新表,以便Master_table中的所有观察都有一个日期。实现此目的的规则:来自Master_table的日期将用作Date存在的日期。否则,将使用Table_A,Table_B和Table_C中的最小日期。如果所有表中都缺少日期,则删除观察结果。
期望输出
ID Problem Date
101 123 01-02-1993
102 125 06-30-1994
103 126 08-22-1999
103 131 08-08-1999
我尝试了什么
SELECT ID, Problem, MIN(Date) as Date
FROM
( SELECT ID, Problem, Date
FROM Table_A
UNION ALL
SELECT ID, Problem, Date
FROM Table_B
UNION ALL
SELECT ID, Problem, Date
FROM Table_C
) as subQuery
Delete From table Where Date IS NULL
答案 0 :(得分:0)
看来你需要以这种方式在3个表之间建立联盟
select id, problem, data
from Table_A
where date is not null
union
select id, problem, min(data)
from Table_B
group by id, problem
where date is not null
union
select id, problem, min(data)
from Table_B
group by id, problem
where date is not null