获取别名的总和

Getting sum of an alias

尝试计算别名 studentsnotreviewed 的总和,解决此问题的最佳方法是什么我一直在尝试不同的方法。我想获取别名 studentsnotreviewed 的总数。

select x.* from
(
select s.id as School,
e.id as examID, e.exam_start as examstart, e.exam_end as examend, 
(select count(*) from students st where e.id=st.exam_id and (st.review_flag='' or st.review_flag is null)) as studentsnotreviewed,
e.exam_end + Interval 2 day as 'DueDate',
(select SUM(studentsnotreviewed)) as SUM
from exams e
#left join exams on st.exam_id = e.id
left join schools s on e.school_id=s.id

where e.exam_start < now() and e.exam_start>'2021-01-01' and e.practice=0) as x
where studentsnotreviewed>0 and (studentsnotreviewed>15 or examend < now())
order by duedate asc, studentsnotreviewed desc

[示例数据]

School examID examstart examend studentsnotreviewed duedate sum
343 458092 Mar 16, 2021, 3:52 PM Aug 28, 2017, 12:59 AM 2 Aug 30, 2017, 12:59 AM 2
125 360216 Jan 7, 2021, 11:55 AM Jul 26, 2018, 11:17 PM 27 Jul 28, 2018, 11:17 PM 27

[期望的结果] studentsnotreviewed 的别名之和。

Total studentsnotreviewed
29

我相信元数据库支持 WITH,因此您可以将整个查询别名作为一个临时数据块,然后像 table:

一样重用它
with x as
(
  select 
    s.id as School,
    e.id as examID, 
    e.exam_start as examstart, 
    e.exam_end as examend, 
    (select count(*) from students st where e.id=st.exam_id and (st.review_flag='' or st.review_flag is null)) as studentsnotreviewed,
    e.exam_end + Interval 2 day as 'DueDate',
  from
    exams e
    left join exams on st.exam_id = e.id
    left join schools s on e.school_id=s.id
  where e.exam_start < now() and e.exam_start>'2021-01-01' and e.practice=0
) 

select
  x.*,
  (select SUM(studentsnotreviewed) from x) as SUM
from
  x
where 
  studentsnotreviewed>0 and 
  (studentsnotreviewed>15 or examend < now())
order by 
  duedate asc, studentsnotreviewed desc

你的查询似乎有一个轻微的语法错误 - 你在外部查询中提到了 # 而没有提到 students st。我相信你可以解决这个问题

我假设您希望 29 作为结果集中重复的值。如果你真的只是想要一个单一的值 29,我想它可以通过以下方式给出:

select count(*) 
from 
  exams e 
  inner join students st on e.id=st.exam_id 
where
  (st.review_flag='' or st.review_flag is null) and
  e.exam_start < now() and e.exam_start>'2021-01-01' and 
  e.practice=0