我将用 SQL 示例来回答。我不知道上面的代码在 PHP 中是如何工作的,但是由于按“BIRTH_DATE”分组,每个年龄会得到不止一行,并且在返回时可能会出现问题。
如果我理解您需要的是 SUM over count(*) 但如果查询没有在任何地方重复使用并且您不需要 count perbirth_date 您只需从查询构造中删除 group by。
见下文,
create table StaffEmployment
( name varchar2(100)
, gender varchar2(10)
, job_cadre varchar2(50)
, birth_date date
);
----------------------------------------------------------------------
insert all
into staffemployment(name,gender,job_cadre,birth_date)
values('A','M','Acdemic',sysdate-(45*365))
into staffemployment(name,gender,job_cadre,birth_date)
values('B','M','Acdemic',sysdate-(45*365))
into staffemployment(name,gender,job_cadre,birth_date)
values('C','F','Acdemic',sysdate-(70*365))
into staffemployment(name,gender,job_cadre,birth_date)
values('D','F','Acdemic',sysdate-(10*365))
SELECT * FROM dual;
----------------------------------------------------------------------
select t.*,TRUNC(months_between(sysdate, BIRTH_DATE) / 12) age
from StaffEmployment t;
----------------------------------------------------------------------
NAME GENDER JOB_CADRE BIRTH_DAT AGE
----- ---------- ---------- --------- ----------
A M Acdemic 13-AUG-75 44
B M Acdemic 13-AUG-75 44
C F Acdemic 19-AUG-50 69
D F Acdemic 04-AUG-10 9
----------------------------------------------------------------------
select BIRTH_DATE,count(*)
from StaffEmployment t
where TRUNC(months_between(sysdate, BIRTH_DATE) / 12) >= 40
and TRUNC(months_between(sysdate, BIRTH_DATE) / 12) < 70
group by BIRTH_DATE;
----------------------------------------------------------------------
BIRTH_DAT COUNT(*)
--------- ----------
13-AUG-75 2
19-AUG-50 1
----------------------------------------------------------------------
And if we do a sum you get the actual count over all rows
----------------------------------------------------------------------
select SUM(count(*)) teacing_count
from StaffEmployment t
where TRUNC(months_between(sysdate, BIRTH_DATE) / 12) >= 40
and TRUNC(months_between(sysdate, BIRTH_DATE) / 12) < 70
group by BIRTH_DATE;
----------------------------------------------------------------------
TEACING_COUNT
-------------
6