SQL查询以选择记录,这些记录根据给定的条件检查至少一条有效记录

时间:2019-03-22 09:26:22

标签: sql sql-server

我当时正在与用户制定具有不同资格的资格表查询。

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

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的用户不符合条件。

NB:状态“有效”并不表示其有效。我们还必须检查日期范围。

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

3 个答案:

答案 0 :(得分:1)

这些是合格用户的条件:

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'
)

答案 1 :(得分:0)

您之前尝试过吗?

select * from users u
where exists(select 0 from eligible e
where u.user_id = e.user_id and 
'2019-03-22' between e.start_date and e.end_date and
e.status<> 'inactive')

答案 2 :(得分:0)

这为您带来了什么?

select * from users u
LEFT join eligibility e on users.id=eligibility.user_id
where e.user_id is NULL
相关问题