SQL SELECT ORDER BY multiple columns depending on value of other column

大兔子大兔子 提交于 2019-12-11 03:32:47

问题


I have a table with the following columns:

id | revisit (bool) | FL (decimal) | FR (decimal) | RL (decimal) | RR (decimal) | date

I need to write a SELECT statement that will ORDER BY on multiple columns, depending on the value of the 'revisit' field.

  1. ORDER BY 'revisit' DESC - records with this field having the value 1 will be first, and 0 will be after
  2. If 'revisit' = 1 order by the lowest value that exists in FL, FR, RL and RR. So if record 1 has values 4.6, 4.6, 3.0, 5.0 in these fields, and record 2 has values 4.0, 3.1, 3.9, and 2.8 then record 2 will be returned first as it holds a lowest value within these four columns.
  3. If 'revisit' = 0 then order by date - oldest date will be first.

So far I have the 'revisit' alone ordering correctly, and ordering by date if 'revisit' = 0, but ordering by the four columns simultaneously when 'revisit' = 1 does not.

SELECT *
FROM vehicle
ORDER BY
`revisit` DESC,
CASE WHEN `revisit` = 1 THEN `FL` + `FR` + `RR` + `RL` END ASC,
CASE WHEN `revisit` = 0 THEN `date` END ASC

Instead it seems to be ordering by the total of the four columns (which would make sense given addition symbols), so how do I ORDER BY these columns simultaneously, as individual columns, rather than a sum.

I hope this makes sense and thanks!


回答1:


In your current query, you order by the sum of the four columns. You can use least to get the lowest value, so your order by clause could look like:

SELECT *
FROM vehicle
ORDER BY
  `revisit` DESC,
  CASE WHEN `revisit` = 1 THEN LEAST(`FL`, `FR`, `RR`, `RL`) END ASC,
  CASE WHEN `revisit` = 0 THEN `date` END ASC

Of course this would sort only by the lowest value. If two rows would both share the same lowest value, there is no sorting on the second-lowest value. To do that is quite a bit harder, and I didn't really get from your question whether you need that.



来源:https://stackoverflow.com/questions/30076307/sql-select-order-by-multiple-columns-depending-on-value-of-other-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!