2013-02-13 89 views
2

我想獲得從子查詢返回的結果的總數。這是我的查詢:如何獲取Postgresql中子查詢返回的結果總數?

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 

然而,當我嘗試執行此,我得到這個錯誤:

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 

我該怎麼辦呢?我正在使用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

這兩個建議工作,謝謝! – 2013-02-13 18:57:48

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'究竟做了什麼? – 2013-02-13 18:59:04

+0

@DiZou:'count(*)over()'是一個使用'count(*)'作爲窗口函數的例子 - 參見http://www.postgresql.org/docs/9.1/static/tutorial-window。 html。 'count_all'是列別名 - 'as'是可選的。 – 2013-02-13 19:01:27

+0

啊,好的。非常感謝你! – 2013-02-13 19:21:55