我想将一张表中符合特定条件的记录数与另一张表中的值进行比较,以确保它们基于id匹配。我有2个表格,SUMMARY和WORKTABLE
SUMMARY
-------------
ID | Total |
y83 | 1 |
u34 | 2 |
-------------
Worktable
-------------
ID | Action | Code
y83| S | T1
y83| S | T1
y83| G | M1
u34| G | M1
u34| G | M1
u34| H | L1
我对以下与汇总总数匹配的计数感兴趣:
select ID, count(ID) from WORKTABLE where ACTION = 'G' and CODE = 'M1' group
by ID;
我的问题是,如何将上面查询的计数与摘要表中的“总计”字段进行比较?
答案 0 :(得分:0)
这应该满足您的需求。
这将使用具有ID的查询并计算您的查找并将该查询的结果联接到Summary表中,并且仅返回匹配的结果。
SELECT *
FROM SUMMARY
INNER JOIN (
SELECT ID, count(ID) AS CountTotal
FROM WORKTABLE
WHERE ACTION = 'G'
AND CODE = 'M1'
) SUB ON SUMMARY.ID = SUB.ID AND SUMMARY.Total = CountTotal
答案 1 :(得分:0)
您需要类似的东西吗?使用inner join
会很有用:
select w.ID, count(w.ID) as WCount, count(s.ID) as SCount
from WORKTABLE w
inner join SUMMARY s on s.ID=w.ID
where w.ACTION = 'G' and w.CODE = 'M1'
group by w.ID;