MS Access - 带有 group by 和 having 子句的 where 子句

MS Accesss - where cluase with group by and having clause

以下是部分数据,在Access中:

icode   soldQty rackQty      dt
---------------------------------------
14000   10      50       03/17/22 20:35
15000    1      45       03/17/22 15:35
16000    3      55       03/17/22 08:22
14000   30      48       03/18/22 14:05
15000   18      62       03/17/22 13:35
16000    3      47       03/17/22 15:23
14000    1      49       03/19/22 16:35
17000    1      49       03/17/22 15:13
14000   24      26       03/17/22 10:35
15000   10      33       03/17/22 20:37

icode有100多个,我只举3个为例。 我想根据特定时间段生成每周(或某些日期之间)报告。 比如说,每周报告在 10:00 到 17:00 之间,针对 3 个项目,14000、15000 和 16000。我期望的输出是:

icode   soldQty rackQty
14000   54         74
15000   19        107
16000    4         96

使用这个查询,我能够得到总和。

select icode, sum(soldQty), sum(rackQty) from sales 
group by icode having icode between 14000 and 16000 
order by icode

我不知道该把 where clause 放在哪里,这样我才能有一个条件 时序(10:00 到 17:00)约束?

试试这个:

select icode, sum(soldQty), sum(rackQty) 
from sales 
where TimeValue(dt) between #10:00:00# and #17:00:00#
group by icode 
having icode between 14000 and 16000 
order by icode

所有条件都应该放在WHERE子句中。

HAVING 子句用于包含 SUM()COUNT() 等聚合值的条件,并在聚合后处理:

SELECT icode, 
       SUM(soldQty) AS total_soldQty, 
       SUM(rackQty) AS total_rackQty 
FROM sales 
WHERE icode BETWEEN 14000 AND 16000
  AND TimeValue(dt) BETWEEN #10:00:00# AND #17:00:00#
GROUP BY icode  
ORDER BY icode;