SQL---Case

Source: Internet
Author: User

In a database, there are two ways to compare data,

First: No conditional judgment on any column

SELECT student_id  As study number, Chinese as English results,case when Chinese >=" excellent "when中文版 >= and english<=' pass 'when中文版<  - ' inferior lattice ' END as describes the FROM dbo. Score

The result of the execution is:

School Number English score Describe
1 120 Excellent
2 100 Pass
3 55 Fail to pass
4 59 Fail to pass
5 60 Pass

Judging from case, judging what? I don't know, when the time begins, we know what to judge, similar to the If...esle If...else in C #.

Second: Direct case column, value judgment 

1 ' School Number is 1 '  2' study number 2'3' study number 3'   4 ' School number is 4 ' endfrom dbo.   Student

The result of the execution is:

(No column name)
School Number is 1
School Number is 2
School Number is 3
School Number is 4
Null

If you see that the last one is null, neither satisfies the case condition, and if there is no else statement, the default is to return a null value.

From the case start, know to judge the value of the StudentID, if it is 1, the output "study number 1", followed by and so on ...

Equivalent to switch (conditional) case in C #

SELECT Case Studentidwhen1Then'School Number is 1' when2Then'School Number is 2' when3Then'School Number is 3' when4Then'School Number is 4'ELSE'Anonymous'endfrom dbo. Student

The result of this SQL execution is:

(No column name)
School Number is 1
School Number is 2
School Number is 3
School Number is 4
John doe

Case for multiple columns:

SQL---Case

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.