SQL DB2:我需要根据查询结果过滤结果
SQL DB2: I need to filter results based on query results
我需要获取给定输入 employee_id 和给定输入日期的 ID:
条件:我需要查询在给定日期或输入中给定日期之前注册的员工。
约束:员工不应在给定输入日期或之前具有 'disEnrolled' 状态。
例如:如果 employee_id 是 32456 和 32458,给定的输入日期是 2021-01-01,则预期结果是 id 值 3,employee_Id - 32458。 employee_Id (32456) 不合格,因为他已在给定的输入日期当天或之前退出。
我有一个 table 包含以下几列:
id
date
status
employee_Id
1
2021-01-01
enrolled
32456
2
2021-01-01
disEnrolled
32456
3
2020-01-01
enrolled
32458
下面是我试过的:
select a.ID
from EMPLOYEE a
where (a.employee_id='34526'
or a.employee_id = '32547')
and (
(a.status= 'enrolled'
and {d '2021-10-10'} >= p.date
)
or (a.status NOT IN 'disEnrolled'
and {d '2021-10-10'} <= a.date
)
);
您可以使用简单的 EXISTS 子句来获得所需的结果 -
SELECT Id
FROM EMPLOYEE E
WHERE status = 'enrolled'
AND NOT EXISTS (SELECT NULL
FROM EMPLOYEE E2
WHERE E.employee_Id = E2.employee_Id
AND E2.status = 'disEnrolled')
AND date <= DATE '2021-01-01'
AND Employee_ids IN (empId_1, empId_2, .....); -- Youe Employee ID list
但此查询将生成 2 条记录,分别为 32457 和 32458,而不仅仅是 32458。
WITH TAB (id, date, status, employee_Id) AS
(
VALUES
(1, '2021-01-01', 'enrolled', 32456)
, (2, '2021-01-01', 'disEnrolled', 32456)
, (4, '2020-01-01', 'enrolled', 32458)
)
SELECT DISTINCT employee_Id
FROM TAB A
WHERE status = 'enrolled'
AND NOT EXISTS
(
SELECT 1
FROM TAB B
WHERE B.employee_ID = A.employee_Id
AND B.status = 'disEnrolled'
AND B.date <= '2021-01-01'
)
我需要获取给定输入 employee_id 和给定输入日期的 ID:
条件:我需要查询在给定日期或输入中给定日期之前注册的员工。
约束:员工不应在给定输入日期或之前具有 'disEnrolled' 状态。
例如:如果 employee_id 是 32456 和 32458,给定的输入日期是 2021-01-01,则预期结果是 id 值 3,employee_Id - 32458。 employee_Id (32456) 不合格,因为他已在给定的输入日期当天或之前退出。
我有一个 table 包含以下几列:
id | date | status | employee_Id |
---|---|---|---|
1 | 2021-01-01 | enrolled | 32456 |
2 | 2021-01-01 | disEnrolled | 32456 |
3 | 2020-01-01 | enrolled | 32458 |
下面是我试过的:
select a.ID
from EMPLOYEE a
where (a.employee_id='34526'
or a.employee_id = '32547')
and (
(a.status= 'enrolled'
and {d '2021-10-10'} >= p.date
)
or (a.status NOT IN 'disEnrolled'
and {d '2021-10-10'} <= a.date
)
);
您可以使用简单的 EXISTS 子句来获得所需的结果 -
SELECT Id
FROM EMPLOYEE E
WHERE status = 'enrolled'
AND NOT EXISTS (SELECT NULL
FROM EMPLOYEE E2
WHERE E.employee_Id = E2.employee_Id
AND E2.status = 'disEnrolled')
AND date <= DATE '2021-01-01'
AND Employee_ids IN (empId_1, empId_2, .....); -- Youe Employee ID list
但此查询将生成 2 条记录,分别为 32457 和 32458,而不仅仅是 32458。
WITH TAB (id, date, status, employee_Id) AS
(
VALUES
(1, '2021-01-01', 'enrolled', 32456)
, (2, '2021-01-01', 'disEnrolled', 32456)
, (4, '2020-01-01', 'enrolled', 32458)
)
SELECT DISTINCT employee_Id
FROM TAB A
WHERE status = 'enrolled'
AND NOT EXISTS
(
SELECT 1
FROM TAB B
WHERE B.employee_ID = A.employee_Id
AND B.status = 'disEnrolled'
AND B.date <= '2021-01-01'
)