我正在搜索为每个工地提供的服务表(从满足特定条件的工地表中)。我想要为每个工作站点提供的服务计数,其中计数是在特定日期范围内提供服务且在此范围之后没有服务的工作站点。
我的查询检索自特定日期以来的记录,但我无法找出执行日期范围条件的代码。我尝试使用 WHERE MAX() 作为子查询的一部分,但这给了我一个错误:
SQL 错误 (147):聚合可能不会出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,并且被聚合的列是外部引用。
如有任何建议,我们将不胜感激。
select
emp.company,
emp.col_empid,
emp.siccode,
empworksite.worksiteid,
empworksite.location,
empworksite.city,
empworksite.zip,
(select
count (col_worksiteid)
from serviceplan
where serviceplan.col_worksiteid = empworksite.worksiteid
AND serviceplan.servicecode IN ('EJO','JF','SE','JT')
AND serviceplan.createdate >= '10/01/2022 00:00') as count_of_services
from empworksite
join emp on emp.col_empid = empworksite.col_empid
join tbl_empxregistration on tbl_empxregistration.col_empid = empworksite.col_empid
WHERE empworksite.lwia = '14' AND emp.joborders = '1' AND tbl_empxregistration.col_reg_type_id = '3' AND emp.typeemp = '5' AND emp.siccode NOT LIKE '11%' AND empworksite.active = '1'
ORDER By count_of_services DESC
我假设您想要计算 2023 财年为 2024 财年没有服务的每个工地提供的服务,其中 2023 财年和 2024 财年是日期范围?
试试这个
select e.col_empworksite, count(s2023.servicecode)
from empworksite e
left outer join serviceplan s2023 on s2023.col_empworksite = e.col_empworksite and s2023.createdate between <FY2023_RANGE>
where not exists (select 1 from serviceplan s2024 where s2024.createdate between <FY2024_RANGE> and s2024.col_empworksite = s2023.col_empworksite)
group by e.col_empworksite