我试图在同一列上获得两个不同的计数。第一个计数在给定的约束下工作正常,但是第二个计数未正确计数。我有两个表,分别是DailyFieldRecord
和AB953
。 DailyFieldRecord
包含:DailyFieldRecordID
和ActivityCodeID
。 AB953
表包含:DailyFieldRecordID, ItemID, and GroupID
。 Count1
将返回包含DailyfieldrecordID's
和ActivityCodeID=387
而没有GroupID=260
的{{1}}的计数。 ItemID in (1302,1303,1305,1306)
将返回包含Count2
和DailyfieldrecordID's
且具有ActivityCodeID=387
的{{1}}的计数。我正在尝试仅获取与上述约束相对应的每个GroupID=260
的{{1}}的数量。
ItemID in (1302,1303,1305,1306)
答案 0 :(得分:0)
首先需要标识所有指定了DailyFieldRecordID
中任何一个的ItemID
,这就是这里的子查询所要做的。然后,可以根据子查询的结果集中存在的位置来确定外部查询中的记录是属于Count1
还是Count2
。
select sum(case when i.DailyFieldRecordID is null then 1 else 0 end) as Count1
, sum(case when i.DailyFieldRecordID is null then 0 else 1 end) as Count2
from AB953 as ab
inner join DailyFieldRecord as dfr on ab.DailyFieldRecordID = dfr.DailyFieldRecordID
left join (
select distinct a.DailyFieldRecordID
from AB953 as a
where a.ItemID in (1302, 1303, 1305, 1306)
) as i on ab.DailyFieldRecordID = i.DailyFieldRecordID
where dfr.ActivityCodeID = 387
and ab.GroupID = 260
最终输出:
+--------+--------+
| Count1 | Count2 |
+--------+--------+
| 4 | 3 |
+--------+--------+