Home Database Mysql Tutorial SQL Server高级内容之case语法函数概述及使用

SQL Server高级内容之case语法函数概述及使用

Jun 07, 2016 pm 05:54 PM
case function

本文将详细介绍下Case函数的用法感兴趣的你可以参考下,或许对你有所帮助

1.Case函数的用法
(1)使用类似:switch-case与if-else if。
(2)语法:
    case [字段]
      when 表达式 then 显示数据
      when 表达式 then 显示数据
      else 显示数据
    end
(3)百分制转换素质教育
1)如图:我们要将显示的数据转换成ABCDE,规则是90分以上显示A,80分以上显示B,以此类推。
    

2)执行的SQL语句是:
代码如下:
      Select ID,TestBase,
      Case
        When testBase>=90 then ‘A'
      When testBase>=80 then ‘B'
        When testBase>=70 then ‘C'
        When testBase>=60 then ‘D'
         Else ‘E' end as testBaseLevel,
    testBeyond,testDate from Score

3)最后的执行结果如图所示: 

(4)注意:
    1)写case对应的就写上end。
    2)end后面跟别名(case与end之间相当于一个字段(对象))
(5)和C#的switch-语法作比较
1)C#
      Switch(变量)
      {
        Case 常量1:结果1;break;
        Case 常量2:结果2;break;
        Default :默认结果;break;
      }
2) SQL
      SQL语法我在上面写了,可以对比看一下。
(6)对应的if-else if语法
    1) C#
      If(表达式1) {结果1;}
      else if(表达式2) {结果2;}
      else {默认结果;}
    2)SQL Server
      case
        when 表达式1 then 显示1
        when 表达式2 then 显示2
        else 默认显示
      end
3)举例说明,如果我们存放性别的时候在数据库中是用f,m标识的,现在我们想要用男女标识,SQL语句如下:
代码如下:
       Select ID,Name,stuSex,
        case
          when stuSex='m' then ‘男'
          when syuSex='f' then ‘女'
          else ‘其它'
        end as stuSexType,
      stuDate from Student。

(7)练习案例:
1)在数据库中执行这段代码:
代码如下:
      use Test
      go
      create table PracticeTest
      (
        number varchar(10),
        amount int
      )
      insert into PracticeTest(number,amount) values('RK1',10)
      insert into PracticeTest(number,amount) values('RK2',20)
      insert into PracticeTest(number,amount) values('RK3',-30)
      insert into PracticeTest(number,amount) values('RK4',-10)

2)实现的效果如下:
    

3)可以看出,首先select中应该有三个字段,并且将数据大于0的放到收入中,那么另一个为0,并且将小于0的放到支出里面,另一个为0,下面我们写实现的SQL语句:
代码如下:
       select number as 单号,
        case
          when amount>0 then amount
          else 0
        end as 收入,
        case
          when amount          else 0
        end as 支出
      from PracticeTest

(8)一道面试题的练习:

1)如图:我们写出下面执行的代码,数据库大家自己建或者我在下面附加脚本了,大家制药执行一下即可:

      

2)执行的SQL语句:
代码如下:
  create table Score
      (
        学号 nvarchar(10),
        课程 nvarchar(10),
        成绩 int
      )
      insert into Score values('0001','语文',87)
      insert into Score values('0002','数学',79)
      insert into Score values('0003','英语',95)
      insert into Score values('0004','语文',69)
      insert into Score values('0005','数学',84)

3)实现功能的SQL语句的书写
代码如下:
        select 学号,sum(
        case
          when 课程='语文' then 成绩
          else 0
        end) as 语文,sum(
        case
          when 课程='数学' then 成绩
          else 0
        end) as 数学,sum(
        case
          when 课程='英语' then 成绩
          else 0
        end) as 英语
      from score group by 学号

相信自己,你就是下一个奇迹!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

See all articles