2013-02-13 2 views
2

하위 쿼리에서 반환 된 총 결과 수를 얻으려고합니다. 나는이 작업을 수행하려면 어떻게PostgreSQL에서 하위 쿼리에서 반환 된 총 결과 수는 어떻게 얻습니까?

ERROR: relation "r" does not exist 
LINE 3: ...on_id) as float)/(select count(*) as total from r) * 100.0... 
                  ^

********** Error ********** 

ERROR: relation "r" does not exist 
SQL state: 42P01 
Character: 112 

: 나는 시도하고 이것을 실행할 때, 나는이 오류가, 그러나

select 
    count(r.reason_id) as num, 
    cast (count(r.reason_id) as float)/(select count(*) as total from r) * 100.0 as pct 
from (
    select 
     case 
      when rarreason != 0 then rarreason 
      else rejectreason end as reason_id 
    from 
     workorderlines 
    where 
     (rarreason != 0 or rejectreason != 0) 
    ) as r 

group by 
    r.reason_id 

: 이것은 내 쿼리입니다? PostgreSQL 9.1을 사용하고 있습니다. 감사!

답변

1

당신의 논리를 확인하지 않았나요하지만이처럼 다시 정렬 할 수 있습니다 : 이것은 다른 하나뿐만 아니라 일

with r as (
    select 
     case 
      when rarreason != 0 then rarreason 
      else rejectreason end as reason_id 
    from 
     workorderlines 
    where 
     (rarreason != 0 or rejectreason != 0) 
) 
select 
    count(r.reason_id) as num, 
    cast (count(r.reason_id) as float)/(select count(*) as total from r) * 100.0 as pct 
from r 
group by r.reason_id 
+0

두 가지 제안이 모두 작동합니다. 감사합니다. –

1

시도 :

select 
    count(r.reason_id) as num, 
    cast (count(r.reason_id) as float)/max(r.count_all) * 100.0 as pct 
from (
    select 
     case 
      when rarreason != 0 then rarreason 
      else rejectreason end as reason_id, 
     count(*) over() as count_all 
    from 
     workorderlines 
    where 
     (rarreason != 0 or rejectreason != 0) 
    ) as r 

group by 
    r.reason_id 
+0

, 감사합니다! 나는 질문을하지만 정확히 count (*) over (count_all)는 무엇을합니까? –

+0

@DiZou :'count (*) over()'는 창 함수로'count (*) '를 사용하는 예제입니다 - http://www.postgresql.org/docs/9.1/static/tutorial-window를보십시오. html. 'count_all'은 열 별칭입니다 - 'as'는 선택 사항입니다. –

+0

아, 그래. 고마워요! –

관련 문제