我有2个表,一个(作业)包含作业列表,第二个包含每个作业中记录的详细信息。
Jobs
JobID Count
A 2
B 3
Records
JobID RecordID ToBeProcessed IsProcessed
A A1 1 1
A A2 1 1
B B1 1 1
B B2 1 0
B B3 1 0
我如何能够创建一个查询,列出所有具有值为1的ToBeProcessed计数的作业等于值为1的isProcessed计数?提前致谢。非常感谢任何帮助。
答案 0 :(得分:2)
首先计算ToBeProcessed
设置为1
或IsProcessed
设置为1的项目数:
SELECT
JobID
, SUM(CASE WHEN ToBeProcessed=1 THEN 1 ELSE 0 END) ToBeProcessedIsOne
, SUM(CASE WHEN IsProcessed=1 THEN 1 ELSE 0 END) IsProcessedIsOne
FROM Records
GROUP BY JobID
这会为您提供所有计数,而不仅仅是ToBeProcessedIsOne
等于IsProcessedIsOne
的计数。要确保只获得两者相同的记录,请使用HAVING
子句或嵌套子查询:
-- HAVING clause
SELECT
JobID
, SUM(CASE WHEN ToBeProcessed=1 THEN 1 ELSE 0 END) ToBeProcessedIsOne
, SUM(CASE WHEN IsProcessed=1 THEN 1 ELSE 0 END) IsProcessedIsOne
FROM Records
GROUP BY JobID
HAVING SUM(CASE WHEN ToBeProcessed=1 THEN 1 ELSE 0 END)=SUM(CASE WHEN IsProcessed=1 THEN 1 ELSE 0 END)
-- Nested subquery with a condition
SELECT * FROM (
SELECT
JobID
, SUM(CASE WHEN ToBeProcessed=1 THEN 1 ELSE 0 END) ToBeProcessedIsOne
, SUM(CASE WHEN IsProcessed=1 THEN 1 ELSE 0 END) IsProcessedIsOne
FROM Records
GROUP BY JobID
) WHERE ToBeProcessedIsOne = IsProcessedIsOne
注意:如果ToBeProcessed
和IsProcessed
的类型不允许非零或一的值,则可以将CASE
语句替换为列的名称,例如:
SELECT
JobID
, SUM(ToBeProcessed) ToBeProcessedIsOne
, SUM(IsProcessed) IsProcessedIsOne
FROM Records
GROUP BY JobID
HAVING SUM(ToBeProcessed)=SUM(IsProcessedD)
答案 1 :(得分:0)
如果我没有误解你的问题,你的语句中只需要一个WHERE子句来查看它们何时都等于1。
SELECT
r.JobID AS j_id,
r.RecordID as r_id,
r.ToBeProcessed AS tbp,
r.IsProcessed AS ip
FROM Records AS r
WHERE r.ToBeProcessed = 1 AND r.IsProcessed = 1
GROUP BY j_id;
如果这不是您要求的,请告诉我。
如果它是来自不同表的计数,那么只计算按jobID分组的tbp和ip行,然后在哪里仍然可以做到这一点