How the ORDER by part of SQL Server is used

Source: Internet
Author: User

Order BY common usage I'm not going to mention it.

The needs of the project are changeable
Let's take a look at a few weird sort requests

--Create a table first
CREATE TABLE AI (
ID int NOT NULL,
No varchar (TEN) NOT NULL
)
Go

--insert data into the table
INSERT INTO AI
Select 105, ' 2 '
UNION ALL
Select 105, ' 1 '
UNION ALL
Select 103, ' 1 '
UNION ALL
Select 105, ' 4 '
Go

--The query effect is as follows:
SELECT * from AI
Go
ID no
----------- ----------
105 2
105 1
103 1
105 4

I.
--The required query results are as follows
-that is, the data for no column is ordered by ' 4 ', ' 1 ', ' 2 '
ID no
----------- ----------
105 4
105 1
103 1
105 2

--Solution 1
--Using function charindex
SELECT * from AI
ORDER BY CHARINDEX (No, ' 4,1,2 ')

--Solution 2, and each group is sorted in descending order of IDs
--Using Function case
SELECT * from AI
no= ' 4 ' then 1
When no= ' 1 ' then 2
When no= ' 2 ' then 3
End,id desc

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.