简体   繁体   中英

How to add Flags set to '1 'for a given condition using Oracle Query?

I have a school table and In the below query I am setting up the Flag column as 1 for studentsID, location with attendanceDt >= 20 and year >=2019 and student type as primary.

Could anyone please suggest how to add the flags '1' in the RESULT OUTPUT and return the expected results by refining the below query:-

Select studentID,location,TO_CHAR('attendanceDt','yyyymm') as attendancedate,count(attendanceDt) as Total,1 as Flag from SchoolTable a
where TO_CHAR('attendanceDt','yyyy')>= 2019 and a.studenttype = 'primary'
Having count(attendanceDt)>=20
group by studentID,location,TO_CHAR('attendanceDt','yyyymm');

RESULT OUTPUT:

studentID  location attendanceDt    Total Flag
100         Australia  201908         20   1
101         Australia  201908         21   1 
102         USA        201902         27   1
103         Canada     201901         22   1
102         USA        201902         24   1
103         USA        201902         25   1

I need to refine the above Oracle query to return the results by summing the flags which are =1 where attendanceDt >= 20 corresponding to location and attendance dates.Below is the expected output:-

Expected Output

location attendanceDt  Count(Flag)
Australia  201908          2
USA        201902          3
Canada     201901          1
  select x.location,x.attendancedate,count(x.Flag)t_count from
  ( 
       Select studentID,location,
     TO_CHAR('attendanceDt','yyyymm') as attendancedate,
     count(attendanceDt) as Total,1 as Flag 
     from SchoolTable a
     where TO_CHAR('attendanceDt','yyyy')>= 2019 and a.studenttype = 'primary'
     Having count(attendanceDt)>=20
      group by studentID,location,TO_CHAR('attendanceDt','yyyymm')
 )x group by x.location,x.attendancedate;

You can try something like that

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