[英]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.