在Postgres订购

时间:2015-11-27 13:56:25

标签: sql postgresql sql-order-by

我想以降序范围的顺序获取结果集。以下是我的查询

select quantity_range as quantity_range, count(*) as number_of_items,
sum(amount) as total_amount,
from (
  select *,case
    when quantity between 0 and 500 then '<=500'
    when quantity between 501 and 525 then '501-525'
    when quantity between 526 and 550 then '526-550'
    when quantity between 551 and 575 then '551-575'
    when quantity between 576 and 600 then '576-600'
    when quantity between 601 and 625 then '601-625'
    when quantity between 626 and 650 then '626-650'
    when quantity between 651 and 675 then '651-675'
    when quantity between 676 and 700 then '676-700'
    when quantity between 701 and 725 then '701-725'
    when quantity between 726 and 750 then '726-750'
    else '>750' end as quantity_range
  from Sales )
group by quantity_range order by quantity_range;

我希望我的结果集如下:

<=500   100 100000.00
600-625 10  5000.00
>700    25  25000.00

如何获得此订购?如果我给出Order By子句,那么>700将在第2位。

1 个答案:

答案 0 :(得分:3)

使用RIGHT从字符串中获取最后一个数字:

select quantity_range as quantity_range, count(*) as number_of_items,
sum(amount) as total_amount
from (
  select *,case
    when quantity between 0 and 500 then '<=500'
    when quantity between 501 and 525 then '501-525'
    when quantity between 526 and 550 then '526-550'
    when quantity between 551 and 575 then '551-575'
    when quantity between 576 and 600 then '576-600'
    when quantity between 601 and 625 then '601-625'
    when quantity between 626 and 650 then '626-650'
    when quantity between 651 and 675 then '651-675'
    when quantity between 676 and 700 then '676-700'
    when quantity between 701 and 725 then '701-725'
    when quantity between 726 and 750 then '726-750'
    else '>750' end as quantity_range
  from Sales ) as sub
group by quantity_range 
order by RIGHT(quantity_range,3);

SqlFiddleDemo