1,Equivalent judgment, equivalent to switch case
Case expression
When value1 then returnvalue1
When value2 then returnvalue2
When value3 then returnvalue3
Else defaultreturnvalue
End
For example:
Case level
When 1 then 'Uncle'
When 2 then 'Uncle two'
When 3 then 'Uncle'
End
It is equivalent to a switch and can only be equivalent.
SelectUsername, Uncle level = (
-
- Case Level
- When1Then 'Uncle'
-
- When2Then 'Uncle two'
-
- When3Then 'Uncle'
-
- End
-
- )
- FromUserinfo
Select username, Uncle level = (Case levelwhen 1 then 'Uncle 'when 2 then' second uncle 'when 3 then 'Uncle 'end) from userinfo
The result is :~~~
2. interval judgment
Case
When condition1 then returnvalue1
When condition 2 then returnvalue2
When Condition 3 then returnvalue3
Else defaultreturnvalue
End
Equivalent to if... Else if... Else .... (Interval judgment is supported)
Note: The data types returned after then must be consistent. The data types of returnvalue1, returnvalue2, and returnvalue3 must be consistent.
-
- SelectUsername, age = (
- Case
-
- WhenAgeBetween28And30Then 'Uncle'
-
- WhenAgeBetween25And27Then 'Big youth'
- WhenAgeBetween20And24Then 'Sao year'
-
-
- WhenAge <20Then 'Kid'
-
- Else 'Baby'
- End
-
- )
-
- FromUserinfo2
Select username, age = (case when age between 28 and 30 then 'Uncle 'When age between 25 and 27 then 'Young up' when age between 20 and 24 then' Sao Nian 'when age <20 then 'kid' else 'babe' end) from userinfo2
3. Practical cases
1. user level in general forums
Forum users
Case bbslevel
When 1 then 'creden'
When 2 then 'prawns'
When 3 then 'cainiao'
End
2. Count the total sales amount of each salesperson in the order table, and list the salesperson's name, total sales amount, and title (> gold medals,> silver medals,> bronze medals, otherwise normal)
3. E-commerce users have different levels based on their total consumption.
4. players in the gaming industry
Ticket No. Amount
RMB1 10
RMB2 20
RMB3-30
RMB4-10
Output the preceding table in the following format:
Bill No. Income and expenditure
RMB1 10 0
RMB2 20 0
RMB3 0 30
RMB4 0 10
-
- SelectNumber,
-
- (
-
- Case
- WhenAmount> 0ThenAmount
-
- Else0
-
- End
-
- ) Income,
-
- (
-
- Case
- WhenAmount <0Then ABS(Amount)
-
- Else0
-
- End
-
- ) Expenditure
-
- FromTest
Select number (case when amount> 0 then amountelse 0end), (case when amount <0 then ABS (amount) else 0end) from test