SQL custom sorting

Source: Internet
Author: User

There was a demand for a while ago, and the sorting rules should be arranged according to the user's needs:

Example:

The database is Oracle, which sorts the class fields of table table_example. The class fields include A, B, C, and D.

The user requires that the data in table_example be ordered by class field values C, A, D, and B.

Method 1:

I started to think of a way to add a custom Field custom when selecting, when the class values are C, A, D, and B, the m values are 1, 2, 3, and 4.

When using case when, we can achieve this without adding custom fields:

Teble_exaple

Method 2:

Using Program-side control, the implementation logic is still complicated due to PB, without further research. The idea is as follows: (for reference only, not implemented .)

Dw _. setsort (class =, (class =,. sort

Method 3:

Use the decode function:

Table_example decode (class ,,,,,,,,)

The function with similar functions in sqlserver is charindex.

Method 3 is the most concise solution. I personally feel that in many cases, the functions implemented by SQL are more direct than those implemented by the program.

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.