首页 > 解决方案 > 如何使用 Oracle Query 为给定条件添加设置为“1”的标志?

问题描述

我有一张学校表,在下面的查询中,我将学生 ID 的标志列设置为 1,位置的出勤Dt >= 20 和年份 >=2019,学生类型为主要。

谁能建议如何在结果输出中添加标志“1”并通过改进以下查询返回预期结果:-

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');

结果输出:

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

我需要通过对 =1 的标志求和来优化上述 Oracle 查询以返回结果,其中出席Dt >= 20 对应于位置和出勤日期。以下是预期的输出:-

预期产出

location attendanceDt  Count(Flag)
Australia  201908          2
USA        201902          3
Canada     201901          1

标签: sqloracle

解决方案


  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;

你可以尝试类似的东西


推荐阅读