首页 > 解决方案 > SQL 查询以选择记录,该记录检查至少一条具有给定条件的有效记录

问题描述

我正在制定一个资格表查询,用户可以有不同的资格。

表格将具有以下给定格式。

id | start_date | end_date | status | user_id
---------------------------------------------

为此,我必须让所有具有有效资格的用户。下面添加了相同的查询。

select *
from users u
  inner join eligibility e on users.id=eligibility.user_id
where e.start_date <= '2019-03-22'
  and e.end_date >= '2019-03-22'
  and e.status<> 'inactive'

这很好用,当至少有一个符合查询中给出的标准的有效资格记录时,我将获得合格用户。

现在我必须检查所有使用这些记录的不合格用户。

基本上,我们将不得不选择没有有效资格记录的用户。如果用户具有至少一个资格记录,则该用户被称为资格。

下面添加了示例数据和预期结果。

用户表:-

id | first_name | last_name
---------------------------
1  |    John    |  Doe
2  |    Sam     |  Ronald
3  |   Alice    |  Wayne
4  |    Dean    |  Marcus
5  |    Bony    |  Ignatius
6  |    Kim     |  Pharm
7  |   Tony     |  Ryan

资格表:-

id | start_date | end_date    | status | user_id
-------------------------------------------------
 1    2018-06-23  2018-12-31  | active |   1
 2    2018-06-23  2019-01-30  | active |   1
 3    2018-06-23  2018-12-31  | active |   3
 4    2018-06-23  2019-12-22  | active |   3
 5    2018-06-23  2018-12-31  |inactive|   4
 6    2018-06-23  2019-03-10  | active |   4
 7    2018-06-23  2018-12-31  | active |   5
 8    2018-06-23  2019-12-31  | active |   5
 9    2018-06-23  2018-01-31  | active |   6
 10   2018-06-23  2019-12-24  | active |   6
 11   2018-06-23  2018-12-31  |inactive|   7
 12   2018-06-23  2019-02-22  | active |   7
 13   2018-06-23  2019-12-31  | active |   1
 14   2018-06-23  2019-12-31  | active |   3

有了这些数据和当前日期,ID 为 1、3、5 和 6 的用户就有资格。id 为 2(没有资格记录)、4 和 7 的用户如果查看数据,则不符合资格。

注意:状态“活跃”并不意味着它是活跃的。我们还必须检查日期范围。

现在我想知道如何查询不合格的用户。

标签: sqlsql-server

解决方案


这些是合格用户的条件:

e.start_date <= '2019-03-22' and e.end_date >= '2019-03-22' and e.status<> 'inactive'

因此,如果表eligibility中没有满足这些条件的用户行,则该用户不合格。
您可以使用not exists

select u.* from users u 
where not exists (
  select 1 from eligibility
  where 
    u.id = user_id 
    and
    start_date <= '2019-03-22' and end_date >= '2019-03-22'
    and 
    status <> 'inactive'
)

推荐阅读