我已经看过这两个问题:
但是,它们都使用聚合函数 MAX 来获得最高值或填充值,这对我的情况不起作用。
出于这个问题的目的,我已经简化了我的情况。这是我目前的数据:
我想获取每条路线的运营商名称,但与行进方向有关(即排序或“首选”值)。这是我的伪代码:
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`
我当前的 SQL 查询是:
SELECT route, operatorName
FROM test
GROUP BY route
这给了我分组,但我的目的是错误的运算符:
route | operatorName
--------------------
95 | James
96 | Mark
97 | Justin
我试过应用一个ORDER BY
子句,但GROUP BY
优先。我想要的结果是:
route | operatorName
--------------------
95 | Richard
96 | Andrew
97 | Justin
我不能在MAX()
这里做,因为“北”按字母顺序排在“南”之前。GROUP BY
在应用该条款之前,我如何明确说明我的偏好/排序?
还要记住,空字符串不是首选。
请注意,这是一个简化的示例。实际查询选择了更多字段并与其他三个表连接,但查询中没有聚合函数。