2015-11-27 5 views
1

Я хочу получить результирующий набор в порядке убывания. Ниже мой запросЗакажите в Postgres

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 

Как получить этот заказ? Если я дам предложение «Порядок по заказу», то >700 выйдет на 2-ое место.

ответ

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

+0

Он отлично работает. У меня есть еще один запрос для отображения диапазона значений. Там моя сумма будет $ 1,000,00- $ 2000,00' '$ 9,000.00- $ 10,000.00' и, наконец,'> $ 10,000.00' Как сделать эту работу? –

+0

@SatheshS Задайте новый вопрос, и вы получите ответ + Подготовьте http://sqlfiddle.com, чтобы мы могли помочь вам быстро – lad2025

Смежные вопросы