sql - 在 Postgres 中排序

标签 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 排在第二位。

最佳答案

使用 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

关于sql - 在 Postgres 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33958945/

相关文章:

database - 在数据库中搜索字符串 'somewhere'

java - Gson Postgres 时间戳序列化

PostgreSQL 在订购时除以零

mysql - sql 选择如果和排序依据

android - sqlite "DROP TABLE IF EXISTS"android中的错误

postgresql - 在 INSERT 期间计算列值

sql - 如何在 oracle 11g 中授予对触发器和同义词的权限

带组的 SQL Order By 子句

c# - 如何在 Entity Framework Code-First 中创建自定义 m2m 表

mysql - SQLite 查找两个表之间的差异