Skip to content
Advertisement

SQL Query for sorting and getting unique count

I have a table which consists of the following details

Customer Deal DealStage
A D1 Lost
A D2 Won
A D3 Contacted
B D4 Conatcted
B D5 Lost
C D6 Lost
D D7 Lost

I have to develop a query where I should get the unique highest stage for each customer. The Stage priority is Won > Contacted > Lost. For Example, A is having three deals which are Won, Lost, and Contacted. So I should be considering Won. Similarly Contacted for B and Lost for C and D

Is it possible to get an Output like

Customer Highets Stage
A Won
B Contacted
C Lost
D Lost

By this, I can generate a pivot table that looks like

Stage CustomerCount
Won 1
Contacted 1
Lost 2

Thanks in Advance

Advertisement

Answer

One option uses aggregation and field():

select customer,
    case min(field(deal_stage, 'Won', 'Contacted', 'Lost'))
        when 1 then 'Won'
        when 2 then 'Contacted'
        when 3 then 'Lost'
    end as highest_stage
from mytable
group by customer

Actually we could combine this with elt():

select customer,
    elt(
        min(field(deal_stage, 'Won', 'Contacted', 'Lost')), 
        'Won', 'Contacted', 'Lost'
    ) as highest_stage
from mytable
group by customer

You can then generate the final result with another level of aggregation:

select highest_stage, count(*)
from (
    select customer,
        elt(
            min(field(deal_stage, 'Won', 'Contacted', 'Lost')), 
            'Won', 'Contacted', 'Lost'
        ) as highest_stage
    from mytable
    group by customer
) t
group by highest_stage
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement