PostgreSQL组由高点组成

时间:2013-09-24 09:17:24

标签: sql postgresql

我有一个PostgreSQL(9.2)数据库,我试图从中获取一些分组数据。小组应该像: 1,2,3,4,5,> 5(高于5)

这可能吗?如果是,怎么样?

到目前为止我所拥有的:

select secondary_diagnoses_count 
from admissions 
group by secondary_diagnoses_count 
order by secondary_diagnoses_count;

1 个答案:

答案 0 :(得分:2)

您的更多数据会很好,但一般情况下您可以使用case

with cte as (
    select
        case
            when secondary_diagnoses_count > 5 then
                '>5'
            else
                secondary_diagnoses_count::text
        end as grp
    from admissions
)
select grp, count(*)
from cte 
group by grp
order by grp

PostgreSQL还允许在group by中使用别名列,因此可以这样编写:

select
    case
        when secondary_diagnoses_count > 5 then
            '>5'
        else
            secondary_diagnoses_count::text
    end as grp
from admissions
group by grp
order by grp

<强> sql fiddle demo