简体   繁体   中英

Oracle SQL Server - sorting/order by how variables are listed in statement

I'm trying to sort a list by how the statement is written, for example:

select state, count(*)
    from some_tbl
    where state = 'WA'
    or zip = 90210
    or city = 'Salt Lake City'

(sorry for the bad example)

I would like to order where WA is on top, CA is second on the list (zip in CA in 90210), and UT (Salt Lake City in in UT) to appear last.

So,

WA  
CA  
UT 

Is there a way to sort the order by how I wrote the query?

You can use a case expression:

order by (case when state = 'WA' then 1
               when zip = '90210' then 2
               else 3
          end)

In the answer to Gordon, i would rewrite it as

order by case when state='WA' then 1
              when state='CA' then 2
              when state='OH' then 3
          end

decode()可以方便地缩短表达式:

order by decode(state, 'WA', 1, 'CA', 2, 'UT', 3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM