2014-10-16 74 views
0

我想計算其中的指令數不等於99999.99,但我很難讓SQL計數函數正常工作。我有以下查詢:SQL計數函數不起作用

select 
    year, college, 
    case 
     when tuition < 99999.99 then 'Other' 
     else to_char(tuition) 
    end tuition, 
    count(*) as tuition_count 
from 
    enrolment 
group by  
    year, college, tuition 
order by  
    year, college, tuition 

我期待以下結果,計算「其他」捲起來。

YEAR COLLEGE  TUITION  TUITION_COUNT 
--------------------------------------------- 
2012 CollegeA Other  123 
2012 CollegeA 99999.99 456 

取而代之,我得到了「其他」的多個實例,每個實例的學費不同。

YEAR COLLEGE  TUITION  TUITION_COUNT 
--------------------------------------------- 
2012 CollegeA Other  100 
2012 CollegeA Other  20 
2012 CollegeA Other  3 
2012 CollegeA 99999.99 456 

回答

1

您需要按(在group by statement中)進行分組。就像這樣:

select year, college, case 
          when tuition < 99999.99 then 'Other' 
          else to_char(tuition) 
         end as tuition, count(*) as tuition_count 
from enrolment 
group by year, college, case 
          when tuition < 99999.99 then 'Other' 
          else to_char(tuition) 
         end 
order by year, college, case 
          when tuition < 99999.99 then 'Other' 
          else to_char(tuition) 
         end 

這看起來更好:

select year, college, tuition, count(*) as tuition_count 
from 
(
    select year, college, case 
          when tuition < 99999.99 then 'Other' 
          else to_char(tuition) 
          end as tuition 
    from enrolment 
) subselect 
group by year, college, tuition 
order by year, college, tuition