SQL Custom Order By Clause

十年热恋 提交于 2019-12-10 20:16:04

问题


A quick Question. I have a query that brings back 2 columns 'Description' and 'Amount' In the Description we have 3 outcomes.

'Gold - owned', 'Bronze - no land' and 'Silver - identified / offered'

I would like the result to show in an order of Gold,Silver,Bronze

Order By Asc or Desc does not achieve this. Is there a way to customize a Order by clause?

Any Help on this Would be appreciated thanks Rusty


回答1:


Inside of a CASE, you may ascribe a numeric value to each and order those ascending. If you will need to query a large table, consider adding an index on Description to improve sorting performance.

ORDER BY
  CASE 
    WHEN Description = 'Gold - owned' THEN 0
    WHEN Description = 'Silver - identified / offered' THEN 1
    WHEN Description = 'Bronze - no land' THEN 2
    ELSE 99 /* Any other value (which you should not have) sorts after all */
  END ASC  /* And don't forget to be explicit about ASC order though it's the default */

Since this works like a normal column in the ORDER BY, if you needed to then sort by the Amount or other column, it can be appended with a comma.

ORDER BY 
  CASE
    WHEN Description = 'Gold '...
  END ASC,
  Amount DESC,
  AnotherColumn ASC



回答2:


Try to use CASE statement:

ORDER BY ( CASE Description
              WHEN 'Gold - owned' THEN 1
              WHEN 'Silver - identified / offered' THEN 2
              WHEN 'Bronze - no land' THEN 3
              ELSE 0
            END)



回答3:


Use this in your order by Clause

order by case description when 'gold' then 1 when 'silver'then 2 else 3 end asc




回答4:


Use CASE in ORDER BY Clause:

ORDER BY 
CASE Description
  WHEN ='Gold - owned' THEN 1
  WHEN = 'Silver - identified / offered' THEN 2
  WHEN = 'Bronze - no land' THEN 3
ELSE 4 END



回答5:


ORDER BY

ORDER BY clause is used to sort data in ascending or descing order.

By default it orders by ascending order if the order is not mentioned.

Syntax:

To order by asc/desc order –

SELECT column_name1,column_name2,… column_nameN   FROM table_name WHERE condition ORDER BYcolumn_name [ASC | DESC];

Example :

SELECT CustomerId , Name FROM customer_details WHERE CustomerId> 0 ORDER BY CustomerId;

http://academy.comingweek.com/sql-orderby/



来源:https://stackoverflow.com/questions/23909406/sql-custom-order-by-clause

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