I use following query to give me the earned commission of our sales agents.
SELECT * FROM (SELECT agent, COUNT(*) as sales, (4*(SELECT COUNT(*) FROM Sales Sales2 WHERE Sales2.agent=Sales.agent AND finalized_at BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND flow=117)) / (SELECT SUM(uren) FROM Uren WHERE datum BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND agent=Sales.agent) as sph FROM Sales WHERE finalized_at BETWEEN '2020-11-27 00:00:00' AND '2020-11-27 23:59:59' AND flow=117 GROUP BY agent ) r ORDER BY sales * sph desc;
Now I want the output to be sorted by (sales * sph * factor)
. Where factor is 10 if sph > 1.5
and else 7.5.
Is it possible to implement this in the query. If yes how do I achieve this?
It would also be good if calculation would be done in the SELECT
statement like (sales * sph * factor) as commission
and then just use SORT BY commission
.
I hope my question makes any sense.
Advertisement
Answer
You could use condition in order by eg using a case when
SELECT * FROM ( SELECT agent, COUNT(*) as sales, (4*(SELECT COUNT(*) FROM Sales Sales2 WHERE Sales2.agent=Sales.agent AND finalized_at BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND flow=117)) / (SELECT SUM(uren) FROM Uren WHERE datum BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND agent=Sales.agent) as sph FROM Sales WHERE finalized_at BETWEEN '2020-11-27 00:00:00' AND '2020-11-27 23:59:59' AND flow=117 GROUP BY agent ) r ORDER BY sales * sph * (case when sph > 1.5 then 10 else 7.5 end ) desc;