I am trying to achieve the following:
I have a single ORDER BY statement which could vary depending on the value stored in Column A.
For example:
if the Type is Member, sort by member last name if the Type is Group, sort by the Group Name
both in Ascending order.
My best guess for the final statement would be:
SELECT * FROM table WHERE STATUS = 'Active' ORDER BY ((LNAME if TYPE = 'Member') OR (GROUPNAME if TYPE = 'Group')) ASC
I know this is incorrect but cannot find information elsewhere. Any ideas?
@ric in Firebird you can put an order by in a with clause, the effects are just not guaranteed (the sort might be retained when no other steps in the query plan cause a sort).
The ORDER BY clause is used to get the sorted records on one or more columns in ascending or descending order. The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name.
Discussion: If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query. After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary).
CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.
Well, you can use the IF
function in MySQL (Note the emphasis on function
since there's also an unrelated IF
statement)...:
ORDER BY IF(TYPE='Member', LNAME, GROUPNAME) ASC
However, in this case it seems the better choice (From a flexibility standpoint) would be the CASE
statement:
ORDER BY CASE `type` WHEN 'Member' THEN LNAME WHEN 'Group' THEN GROUPNAME ELSE 1 END ASC
Note that the entire block from CASE
to END
is to be considered as a single "unit". The result of which is what you're trying to sort against (Hence why the ASC
comes after the block, rather than inside of it)...
Use the CASE statement.
Example from http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html:
SELECT id, first_name, last_name, birthday FROM table ORDER BY -- numeric columns CASE _orderby WHEN 'id' THEN id END ASC, CASE _orderby WHEN 'desc_ id' THEN id END DESC, -- string columns CASE _orderby WHEN 'first_name' THEN first_name WHEN 'last_name' THEN last_name END ASC, CASE _orderby WHEN 'desc_first_name' THEN first_name WHEN 'desc_last_name' THEN last_name END DESC, -- datetime columns CASE _orderby WHEN 'birthday' THEN birthday END ASC, CASE _orderby WHEN 'desc_ birthday' THEN birthday END DESC;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With