SQL 跨多个表计算记录的问题

Issues with Counting Records with SQL across multiple tables

共有三个 table:案例、呼叫和子事件。

table模式是一个Case可以有多个Call,每个Call可以有多个SubEvent。 我想使用查询来获取特定日期后每个案例的所有调用计数和所有子事件(如果有的话)的计数。

例如,名为 John 的案例有 3 个调用...第一个调用有 2 个子事件,第二个调用有 1 个子事件,第三个调用有零个。所以查询应该return这个结果:

Case Call Total SubEvent Total
John 3 3

我试过用多种方式编写查询,包括子查询等,但我无法让它正常工作。我最接近的是下面的查询,但这提供了不正确的呼叫计数。当它应该给我 3 时它给了我 4。我尝试的另一个例子有 4 个调用和 10 个子事件,但是查询 returned 11 总调用而不是 4.

如果有任何帮助,我将不胜感激。我的 SQL 在一段时间不用后变得生锈了,这是在某人的 Access 数据库中,在编写 SQL 查询时非常善变。

SELECT c.casename, Count(e.callid) AS EventTotal, Count(s.id) AS SubEventTotal
FROM (cases AS c INNER JOIN calls AS e ON c.contactid = e.contactid) left JOIN tblSubEvents AS s ON e.callid = s.callid
WHERE e.calldate > #1/1/2022#
GROUP BY c.casename

试试这个:

SELECT
   c.casename
   ,Count(e.callid) AS EventTotal
   ,sum(s.id) AS SubEventTotal
FROM (cases AS c INNER JOIN calls AS e ON c.contactid = e.contactid)
left JOIN (select callid, count(s.id) as id from tblSubEvents s group by callid) AS s ON e.callid = s.callid
WHERE e.calldate > #1/1/2022#
GROUP BY c.casename

基本上,将 sub-event 计数的责任推给连接查询。

考虑连接两个聚合派生表:

SELECT case.casename, c_agg.EventTotal, e_agg.SubEventTotal
FROM (case
INNER JOIN (
    SELECT contactid, COUNT(callid) AS EventTotal
    FROM calls
    WHERE calldate > CDate('2022-01-01')
    GROUP BY contactid
) c_agg
  ON case.contactid = c_agg.contactid)
LEFT JOIN (
    SELECT callid, COUNT(id) AS SubEventTotal
    FROM tblSubEvents
    GROUP BY callid
) e_agg
  ON c_agg.callid = e_agg.callid