简体   繁体   中英

SQL: How to ORDER BY column(s)

I have a table with two columns. I need to ORDER the first column in ascending order, however when I run my query I don't get the result I'm looking for.

This the current output I'm getting when running my SELECT query:

  Retailer     AccountsOpened

1  Retailer 1  1
2  Retailer 2  1
3  Retailer 3  1
4  Mobichoice  1
5  Retailer 1  3
6  Retailer 2  3
7  Retailer 3  3
8  Mobichoice  3
9  Retailer 1  2
10 Retailer 2  2
11 Retailer 3  2
12 Mobichoice  2

I've tried to ORDER BY Retailer (ASC) and AccountsOpened but that doesn't work. The code I tried is below:

SELECT * FROM Table 1 ORDER BY Retailer ASC, AccountsOpened

The output I want to see should be the following:

  Retailer     AccountsOpened

1  Retailer 1  1
2  Retailer 1  2
3  Retailer 1  3
4  Retailer 2  1
5  Retailer 2  2
6  Retailer 2  3
7  Retailer 3  1
8  Retailer 3  2
9  Retailer 3  3
10 Mobichoice  1
11 Mobichoice  2
12 Mobichoice  3

How can I achieve this?

Use a case expression to put the Mobichoice rows after the different Retailer rows.

SELECT * FROM Table 1
ORDER BY case when Retailer = 'Mobichoice' then 2 else 1 end,
         Retailer ASC, AccountsOpened

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