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

本文将详细介绍下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
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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.