[英]SQL Server join on subquery
我有两个 SQL 表:表 A 和表 B
表A
批处理标识符(varchar) | 批处理状态(位) | dt_utc(日期时间) | 批处理任务 |
---|---|---|---|
batch_id1 | 0 | 2022-09-15 10:00:00 | 1 |
batch_id1 | 1 | 2022-09-15 11:00:00 | 1 |
batch_id2 | 0 | 2022-09-15 10:30:00 | 4 |
表B
批处理标识符(varchar) | 任务状态(位) | 任务描述(varchar) | 任务标识符(varchar) |
---|---|---|---|
batch_id1 | 0 | 2022-09-15 10:00:00 | task_id1 |
batch_id1 | 1 | 2022-09-15 10:50:00 | task_id1 |
batch_id2 | 0 | 2022-09-15 10:30:00 | task_id1 |
batch_id2 | 1 | 2022-09-15 10:35:00 | task_id1 |
batch_id2 | 0 | 2022-09-15 10:36:00 | task_id2 |
batch_id2 | 0 | 2022-09-15 10:37:00 | task_id3 |
我想要做的是以下几点:
获取“进行中”批处理表(即 batch_status = 0)以及已执行的任务。 因此,例如在上面的示例中,唯一仍在运行的批处理是 batch_id2,而相关的已完成任务是 task_id1。
到目前为止,我已经对此进行了测试但没有成功:
select
*
from
(
select
batch_identifier,
MAX(CAST(batch_status as int)) as _status
from
dbo.TableA
group by
batch_identifier
) data
where _status = 0 ??
你能帮忙吗?
batch_identifier
和task_identifier
是 SQL 索引。
也许像其中之一?
SELECT batch_identifier, db_utc, Zero, One
FROM TableA
LEFT JOIN (
SELECT batch_identifier,
SUM(CASE WHEN task_status = 0 THEN 1 ELSE 0 END) AS Zero,
SUM(CASE WHEN task_status = 1 THEN 1 ELSE 0 END) AS One
FROM TableB
GROUP BY batch_identifier
) AS b
ON a.batch_identifier = b.batch_identifier
SELECT *
FROM TableA a
WHERE NOT EXISTS (
SELECT NULL FROM TableB b WHERE b.batch_identifier = a.batch_identifier AND b.task_status = 0
)
如果我对您的理解正确,我认为您不需要子查询。
尝试:
SELECT batch_identifier, task_identifier, MAX(CAST(batch_status as int)) as _status
FROM dbo.TableA a
INNER JOIN dbo.TableB b ON a.batch_identifier = b.batch_identifier AND task_status = 1
WHERE batch_status = 0
GROUP BY batch_identifier, task_identifier
使用公用表表达式来获取哪些批次仍在进行中。 然后我将获取 TableB 中的详细信息,并按批次和任务标识符分组,并检查任务状态中的最大值是否为零(意味着任务仍在进行中)。
WITH data as (
select
batch_identifier
from
dbo.TableA
group by
batch_identifier
having
MAX(CAST(batch_status as int)) = 0)
select
details.batch_identifier,
MIN(CAST(details.task_status as int)) as task_status,
MIN(details.task_description) as task_description,
details.task_identifier
from
dbo.TableB as details
inner join
data on data.batch_identifier = details.batch_identifier
group by
details.batch_identifier,
task_identifier
having
MAX(CAST(details.task_status as int)) = 0
结果:
batch_identifier task_status task_description task_identifier
---------------- ----------- ---------------- ------------
batch_id2 0 2022-09-15 10:36:00 task_id2
batch_id2 0 2022-09-15 10:37:00 task_id3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.