在同一列上使用两个不同的sum()的问题

时间:2019-06-29 18:22:44

标签: tsql

我试图在同一列上获得两个不同的计数。第一个计数在给定的约束下工作正常,但是第二个计数未正确计数。我有两个表,分别是DailyFieldRecordAB953DailyFieldRecord包含:DailyFieldRecordIDActivityCodeIDAB953表包含:DailyFieldRecordID, ItemID, and GroupIDCount1将返回包含DailyfieldrecordID'sActivityCodeID=387而没有GroupID=260的{​​{1}}的计数。 ItemID in (1302,1303,1305,1306)将返回包含Count2DailyfieldrecordID's且具有ActivityCodeID=387的{​​{1}}的计数。我正在尝试仅获取与上述约束相对应的每个GroupID=260的{​​{1}}的数量。

ItemID in (1302,1303,1305,1306)

1 个答案:

答案 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      |
+--------+--------+