I've already looked at these two questions:
However both of them use an aggregate function MAX in order to obtain the highest or filled in value, which doesn't work for my case.
For the purposes of this question, I've simplified my situation. Here is my current data:
I'd like to obtain the operator name for each route, but with respect to direction of travel (i.e. ordering or "preferring" values). This is my pseudo-code:
if(`direction` = 'west' AND `operatorName` != '') then select `operatorName`
else if(`direction` = 'north' AND `operatorName` != '') then select `operatorName`
else if(`direction` = 'south' AND `operatorName` != '') then select `operatorName`
else if(`direction` = 'east' AND `operatorName` != '') then select `operatorName`
My current SQL query is:
SELECT route, operatorName
FROM test
GROUP BY route
This gives me the grouping, but wrong operator for my purposes:
route | operatorName
--------------------
95 | James
96 | Mark
97 | Justin
I have tried applying a ORDER BY
clause but GROUP BY
takes precedence. What my desired result is:
route | operatorName
--------------------
95 | Richard
96 | Andrew
97 | Justin
I cannot do MAX()
here as "north" comes before "south" in alphabetical order. How do I explicitly state my preference/ordering before the GROUP BY
clause is applied?
Also keep in mind that empty strings are not preferred.
Please note that this is a simplified example. The actual query selects a lot more fields and joins with three other tables, but there are no aggregate functions in the query.