SQL自定义排序

时间:2018-10-05 18:14:34

标签: mysql sql

我有一个名为Tasks的表,如下所示。表中的字段是员工,任务和日期。

输入表:

Date:       employees   Task
2016-12-03  John    Paint the walls pink
2016-12-03  Sam     Play hockey on linoleum
2016-12-03  John    the golden fish in a bucket
2016-12-03  Sam     Create a rink on the porch
2016-12-03  Nathan  Glue the front door
2016-12-03  Nathan  Paint the walls pink
2016-12-08  Sam     Melt the doorknob
2016-12-08  Dewey   Wrap the cat in toilet paper
2016-12-08  John    Give bubble gum to the dog
2016-12-08  Dewey   Order 20 pizzas
2016-12-09  John    Create a rink on the porch
2016-12-09  Nathan  Eat all the candies
.......
...... so on

对于“输出”,我想选择一个列表,该列表将首先根据日期进行排序,然后根据员工的特定顺序进行排序(John排名第一,Nathan排名第二,sam排名第三,Dewey排名第四)。

Output:
    Date:       employees   Task
    2016-12-03  John    Paint the walls pink
    2016-12-03  John    the golden fish in a bucket
    2016-12-03  sam     Play hockey on linoleum
    2016-12-03  Sam     Create a rink on the porch
    2016-12-03  Nathan  Glue the front door

..
..
.... so on.

我尝试使用ORDER BY。 如何按上述特定顺序完成排序? 还是我需要了解其他概念? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以使用FIELD()功能。该函数的详细信息是:

FIELD(str,str1,str2,str3,...)
  

返回str1,str2,str3,...列表中str的索引(位置)。   如果找不到str,则返回0。

现在,如果FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey')不在employees中,则('John', 'Nathan', 'Sam', 'Dewey')函数将返回 0

因此,如果仅使用ORDER BY FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey'),则其他不匹配行将显示在顶部。因此,我们可以使用If()函数为其他不匹配行返回 1 ,为匹配的行返回 0

现在,我们可以使用FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey')的另一种排序方式。这样可以确保匹配的ID按照Field()函数中指定的顺序首先出现。

尝试:

SELECT * 
FROM your_table 
ORDER BY `date` ASC, 
          IF(FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey') = 0, 1, 0) ASC, 
          FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey') ASC 

答案 1 :(得分:0)

您可以使用#include <stdint.h>函数:

FIELD()

唯一的警告是您是否还有其他员工。上面的逻辑将它们放在第一位。

因此,您可能需要类似的东西:

SELECT * 
FROM your_table 
ORDER BY `date` ASC, FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey')

我正在使用SELECT * FROM your_table ORDER BY `date` ASC, COALESCE(NULLIF(FIELD(employees, 'John', 'Nathan', 'Sam', 'Dewey'), 0), 999999) 组合以避免重复雇员列表。另一个选择是反向列表:

COALESCE(NULLIF())