如果第一个表上的查询返回没有记录,则从第二个表返回记录

时间:2017-07-21 22:06:46

标签: sql-server

目标是从表address_master返回id_num和county的值(address_master每个id有一个记录)如果在address_history上使用以下查询未返回id_num AND county值:

SELECT DISTINCT a.id_num, a.county FROM address_history a INNER JOIN (SELECT id_num, MIN(archive_job_tim) AS MaxEnrollDate FROM address_history GROUP BY id_num) b ON (a.id_num = b.id_num AND a.archive_job_tim = b.MaxEnrollDate) WHERE addr_cde = '*LHP'

示例数据:

表address_history(包含历史更改,每个id可以有多个记录)

id_num | county | archive_job_tim
-------|--------|----------------
123    |012     |10/17/2001 10:48:38
123    |NULL    |10/17/2001 09:50:02
123    |042     |11/17/2003 08:22:01
134    |NULL    |12/10/2005 02:14:23
145    |534     |9/27/1996 00:00:00

表address_master(仅包含每个id的最新记录)

id_num | county | archive_job_tim
-------|--------|-----------------
123    |563     |12/22/2015 10:29:01
134    |734     |2/23/2005 07:21:15
145    |943     |10/22/1996 06:24:13
168    |012     |6/5/2017 08:01:22
197    |NULL    |7/1/2017 10:16:02

查询结果应为:

id_num | county
-------|--------
123    |012    (because it is the earliest record with a county for this id in address_history)
134    |734    (because the only record(s) in address_history has no county, returns record from address_master)
145    |534    (because it is the earliest record with a county for this id in address_history)
168    |012    (because no record exists in address_history for this id)
197    |NULL   (because no record exists in address_history for this id)

感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

我认为您正在查询如下:

Select top (1) with ties * from
(
    Select *,'am' as Note from address_master
    union all
    Select *,'ah' as Note from address_history
) a where (a.Note = 'ah' and a.county is not null) or a.Note = 'am'
Order by Row_Number() over(partition by id_num order by archive_job_tim)

输出如下:

+--------+--------+-------------------------+------+
| id_num | county |     archive_job_tim     | Note |
+--------+--------+-------------------------+------+
|    123 | 12     | 2001-10-17 10:48:38.000 | ah   |
|    134 | 734    | 2005-02-23 07:21:15.000 | am   |
|    145 | 534    | 1996-09-27 00:00:00.000 | ah   |
|    168 | 12     | 2017-06-05 08:01:22.000 | am   |
|    197 | NULL   | 2017-07-01 10:16:02.000 | am   |
+--------+--------+-------------------------+------+