简体   繁体   中英

How to use a calculated value in Oracle SQL count

I have a column called BIRTH_DATE in my view. I want to calculate the age using that column and today's date, and count the number of staff in an age bracket. For example: staff between 40 and 49 etc.

Other answers in plain SQL statements are also welcome.

My code is shown below:

$count = StaffEmploymentListView::find()
        ->select([
            'COUNT(*) AS TEACHING_COUNT', 
            'BIRTH_DATE' => 'BIRTH_DATE'
        ])
        ->where(['GENDER' => 'MALE', 'JOB_CADRE' => 'ACADEMIC'])
        ->andFilterHaving(['>=', "TRUNC(months_between(sysdate, BIRTH_DATE) / 12)", 40])
        ->andFilterHaving(['<', "TRUNC(months_between(sysdate, BIRTH_DATE) / 12)", 70])
        ->groupBy(['BIRTH_DATE'])
        ->all();

I am calculating the age as shown below:

TRUNC(months_between(sysdate, BIRTH_DATE) / 12)

After doing this if I try to access the TEACHING_COUNT variable in the model it is null.

I will answer with SQL examples. I don't know how the above code works in PHP but because of the group by "BIRTH_DATE" you will get more than one row per age and it could be issue while returning.

If I understood what you need is SUM over count(*) but if the query is not re-used any where and you don't need count per birth_date you simply can remove the group by from the query construction.

See below,

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

You can count the number of records between an age bracket without needing to write any SQL as well.

$from = date('Y-m-d', strtotime('-49 years'));
$to = date('Y-m-d', strtotime('-40 years'));
$query = StaffEmploymentListView::find()
        ->where(['>=', 'BIRTH_DATE', $from])
        ->andWhere(['<=', 'BIRTH_DATE', $to]);

// You can get the count
$count = $query->count();

// Or use the query to display the results
echo Html::tag('h1',
    'Found ' . $query->count() . ' clients born between ' .
    Yii::$app->formatter->asDate($from) . ' and ' . 
    Yii::$app->formatter->asDate($to)
);
$dataProvider = new ActiveDataProvider([
    'query' => $query
]);

echo GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            'name',
            'BIRTH_DATE:date', 
            [
                'attribute' => 'BIRTH_DATE',
                'value' => static function($model) {
                    return floor((time() - strtotime($model->BIRTH_DATE)) / 31556926);
                },
                'label' => 'Age'
            ]
        ]
]);

Since you are already using yii , it seems to make sense to use its methods directly. In this case the count() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM