The usage of Oracle case when statement _oracle

Source: Internet
Author: User
1. The case-when expression has two forms
Copy Code code as follows:

--Simple Case function
Case Sex
When ' 1 ' THEN ' male '
When ' 2 ' THEN ' woman '
Else ' other ' end
--case search function
Case
When sex = ' 1 ' THEN ' male '
When sex = ' 2 ' THEN ' female '
Else ' other ' end

2. Case when in the statement in different positions in the use
2.1 SELECT Case when usage
Copy Code code as follows:

SELECT grade, COUNT (case when sex = 1 THEN 1/*sex 1 for boys, 2 girls * *
ELSE NULL
End) Number of boys,
COUNT (case when sex = 2 THEN 1
ELSE NULL
End) Number of girls
From students GROUP by grade;

2.2 WHERE Case Usage
Copy Code code as follows:

SELECT t2.*, t1.*
From T1, T2
WHERE (case when t2.compare_type = ' A ' and
T1. Some_type like ' nothing% '
THEN 1
When T2.compare_type!= ' A ' and
T1. Some_type not like ' nothing% '
THEN 1
ELSE 0
end) = 1

2.3 GROUP by case usage
Copy Code code as follows:

SELECT
Case when salary <= THEN ' 1 '
When salary > Salary <= THEN ' 2 '
When salary > Salary <= THEN ' 3 '
When salary > Salary <= 1000 THEN ' 4 '
ELSE NULL End Salary_class,--alias name
COUNT (*)
From Table_a
GROUP by
Case when salary <= THEN ' 1 '
When salary > Salary <= THEN ' 2 '
When salary > Salary <= THEN ' 3 '
When salary > Salary <= 1000 THEN ' 4 '
ELSE NULL end;

3. Other implementations of If-then-else
3.1 DECODE () function
Copy Code code as follows:

Select decode (Sex, ' M ', ' Male ', ' F ', ' Female ', ' Unknown ')
From employees;

It appears that only Oracle provides this function, and does not support ANSI SQL, the syntax is not clear when the case, the individual does not recommend use.
3.2 Special implementations in the Where
Copy Code code as follows:

SELECT t2.*, t1.*
From T1, T2
WHERE (t2.compare_type = ' A ' and T1. Some_type like ' nothing% ')
OR
(T2.compare_type!= ' A ' and T1.) Some_type not like ' nothing% ')

This method is also used under special circumstances, to pay more attention to logic, do not make mistakes.
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.