选择一个计数和一个大于一个的最大值的计数

时间:2019-03-19 10:34:27

标签: sql oracle oracle11g

我有一个查询,需要计算一些列的计数和一列最大值的计数,然后再按其他条件分组。

到目前为止,我有以下查询:

select 
subj.inventoryNum as Inventory,
extract(month from subj.createDate) as month,
oolame.schoolCode as Code,
count(case when max(subVers.verNum) > 0 then 1 end) as deleted,
count(case when subVers.delDate is not null then 1 end) as changed

from 
Subjects subj
inner join SubjectVersions subVers on subVers.subjFk = subj.subjId
inner join SchoolName oolame on oolame.oolameId = subj.oolameFk 

group by 
subj.inventoryNum,
extract(month from subj.createDate),
oolame.schoolCode;

它给我以下错误:

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"
*Cause:    
*Action:
Error at Line: 2 Column: 1

1 个答案:

答案 0 :(得分:1)

您要做什么尚不清楚。您是否想要整体最大值?每个科目的最高分?其他最大值?

在任何情况下,都可以在子查询中使用窗口函数来获取最大值。例如,如果您希望每个科目的最高成绩:

select subj.inventoryNum as Inventory,
       extract(month from subj.createDate) as month,
       oolame.schoolCode as Code,
       sum(case when subVers.max_verNum > 0 then 1 else 0 end) as deleted,
       count(subVers.delDate) as changed
from Subjects subj inner join
     (select subvers.*,
             max(subVers.verNum) over (partition by subVers.subjFk) as max_verNum
      from SubjectVersions subVers
     ) subVers
     on subVers.subjFk = subj.subjId inner join
     SchoolName oolame
     on oolame.oolameId = subj.oolameFk 
group by subj.inventoryNum,
         extract(month from subj.createDate),
         oolame.schoolCode;