2

我正在尝试获取从子查询返回的结果总数。这是我的查询:

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。谢谢!

4

2 回答 2

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
于 2013-02-13T18:50:48.473 回答
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
于 2013-02-13T18:51:05.387 回答