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():

Actually we could combine this with elt():

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement