如何按其他行值排序表结果

时间:2018-11-02 19:39:09

标签: mysql sql

我创建了一个查询以选择存在其他行的表中的record列,但是我想添加一个order by,该列按另一行的值排序。

SELECT 
  record 
FROM 
  record_attributes 
GROUP BY 
  record 
HAVING 
  sum(type = 'lead' AND option_name = 'pupil_cap' AND value > 0) > 0 AND 
  sum(type = 'lead' AND option_name = 'car_type' AND value = 'Manual') > 0 AND 
  sum(type = 'lead' AND option_name = 'instructor_areas_covered' AND value = '26') > 0 AND 
  sum(type = 'lead' AND option_name = 'diary_updates' AND value = '1') > 0

如何通过另一个查询在同一表中使用以下数据对这些结果进行排序:

ORDER BY record_attributes.value WHERE record_attributes.type = 'lead' AND record_attributes.option_name = 'instructor_rank'

如果该行不存在,则使用此:

ORDER BY record_attributes.value WHERE record_attributes.type = 'lead' AND record_attributes.option_name = 'instructor_start_date'

1 个答案:

答案 0 :(得分:1)

不确定我是否正确理解。
但是这样吗?

...
ORDER BY 
MAX(CASE WHEN type = 'lead' AND option_name = 'instructor_rank' THEN value END),
MAX(CASE WHEN type = 'lead' AND option_name = 'instructor_start_date' THEN value END)

您可以在妊娠期here对其进行测试。