Question

First question ever so be harsh :)

I am needing to sort by a specific department type or department(s) followed by rank. The default setting orders by Rank, Dept_Type and Department. The front end is PHP but I'm looking more for a SQL fix if possible. I also have a source table of departments if a sub query could work.

Orgin Table:

+-----------+------------+------+
| Dept_Type | Department | Rank |
+-----------+------------+------+
| Inbound   | Dept R     |   1  |
| Outbound  | Dept P     |   2  |
| Inbound   | Dept E     |   3  |
| Outbound  | Dept D     |   4  |
| Outbound  | Dept D     |   5  |
| Outbound  | Dept D     |   6  |
+-----------+------------+------+

I need to specify to order by "Dept D", "Dept E", then everything else like so:

SELECT * 
FROM table 
ORDER BY FIELD(department, "Dept D", "Dept E"), Rank, Dept_Type, Department

What I want it to return (DDDERP):

+-----------+------------+------+
| Dept_Type | Department | Rank |
+-----------+------------+------+
| Outbound  | Dept D     |   4  |
| Outbound  | Dept D     |   5  |
| Outbound  | Dept D     |   6  |
| Inbound   | Dept E     |   3  |
| Inbound   | Dept R     |   1  |
| Outbound  | Dept P     |   2  |
+-----------+------------+------+

What it actually returns(RPDDDE):

+-----------+------------+------+
| Dept_Type | Department | Rank |
+-----------+------------+------+
| Inbound   | Dept R     |   1  |
| Outbound  | Dept P     |   2  |
| Outbound  | Dept D     |   4  |
| Outbound  | Dept D     |   5  |
| Outbound  | Dept D     |   6  |
| Inbound   | Dept E     |   3  |
+-----------+------------+------+

So in theory I want:

ORDER BY FIELD("Dept D", "Dept E", department), Rank

But it obviously does not work that way. Thank you for taking time to look at it.

Était-ce utile?

La solution

Use the DESC attribute:

ORDER BY FIELD(department, 'Dept E', 'Dept D') DESC, Rank, Dept_Type, Department

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top