[英]SQL ORDER BY 1st column, but if 1st column is empty replace the empty value by a value from 2nd column
I have a sql table with several columns, two of which are the start and the finish time of an event.我有一个 sql 表,其中有几列,其中两列是事件的开始时间和结束时间。 The query pulls rows from the table and sorts it by the start time - the finish time is irrelevant for the sorting.查询从表中提取行并按开始时间对其进行排序——结束时间与排序无关。 However in rare cases, there might be an entry without a start time.但是在极少数情况下,可能会有一个没有开始时间的条目。 In this case I want the query to handle it like the start time would be the same value as the finish time, so it isn't placed at the beginning of the table:在这种情况下,我希望查询处理它,就像开始时间与结束时间的值相同一样,因此它不会放在表的开头:
Example Data:示例数据:
| Start | Finish |
| -------- | -------- |
| 15:31:00 | 15:39:00 | 1st Event
| 00:00:00 | 15:36:00 | 2nd Event
| 15:37:00 | 15:42:00 | 3rd Event
The query looks like this:查询如下所示:
SELECT FROM table ORDER BY Start ASC
Obviously what happens now is, that the 2nd Event (with an empty start time) will end up on top or at the bottom of the list, depending on ASC or DESC argument.显然,现在发生的情况是,第二个事件(开始时间为空)将在列表的顶部或底部结束,具体取决于 ASC 或 DESC 参数。
What I want is it to be put in the list as if the start time would also be 15:36:00.我想要的是将其放入列表中,就好像开始时间也是 15:36:00 一样。 As if there was a function to say好像有个function说
If Start is '00:00:00'
then Start = Finish
Doing a COALESCE like像做一个 COALESCE
SELECT FROM table ORDER BY COALESCE(Start, Finish)
is not an option, because events have different lengths and in this example, the finish time of event 2 is before the finish time of event 1 so it would still end up at the beginning of the list.不是一个选项,因为事件有不同的长度,在这个例子中,事件 2 的结束时间早于事件 1 的结束时间,所以它仍然会在列表的开头结束。
Any way to do this directly within the SQL Query?有什么方法可以直接在 SQL 查询中执行此操作?
Best regards!最好的祝福!
You may order using a CASE
expression:您可以使用CASE
表达式进行排序:
SELECT *
FROM yourTable
ORDER BY CASE WHEN Start <> '00:00:00' THEN Start ELSE `End` END;
Note that END
is a keyword in MySQL and so you should avoid naming your columns using it.请注意, END
是 MySQL 中的关键字,因此您应该避免使用它来命名您的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.