当前位置:网站首页>零基础自学SQL课程 | IF函数
零基础自学SQL课程 | IF函数
2022-06-28 10:58:00 【游戏编程】
大家好,我是宁一。
今天是我们的第22课:IF函数。
大家如果学过其他编程语言,应该对IF函数很熟悉了。用来根据条件,返回不同值。
基本语法:
IF(条件表达式, 值1, 值2) 如果条件表达式为True,返回值1,为False,返回值2。
返回值可以是任何值,比如:数值、文本、日期、空值NULL、数学表达式、函数等。
1、 IF函数
实例: 在Students表中,将1995年及之前出生的学生划分为1班,1995年以后出生的学生划分为2班,最后显示Sname,Sage,所在班级这3列。

示例结果:

SELECT Sname, Sage, IF( YEAR(Sage) <=1995, "1班","2班" ) AS "所在班级"FROM Students;2、IF函数嵌套
当分类大于两种时,可以将IF函数嵌套实现。
实例: 在Students表中,学生编号Sid小于等于3的学生,属于1班;Sid为4到6的学生,属于2班;Sid大于等于7的学生属于3班。最后显示Sname,Sage,所在班级这3列。
SELECT Sid, Sname, IF(Sid<=3,"1班", IF(Sid>=7,'3班','2班') ) AS "所在班级"FROM Students
嵌套函数看起来还是有点麻烦的,如果分类大于两种,可以用CASE关键词代替IF函数嵌套,下节课我们会具体讲解。
3、IF+聚合函数
IF函数还经常与聚合函数结合使用,我们来看看实例。
实例: 集合Teacher表和Students,计算班主任所带学生的人数,大于等于5的显示“5人及以上”,人数小于5的显示“5人以下”。

示例结果:

SELECT t.Tname, COUNT(*) AS "学生人数", IF(COUNT(*)>=5,"5人及以上","5人以下") AS "分类"FROM Teachers tJOIN Students sON t.Tid = s.TidGROUP BY t.Tname; 下节课我们讲讲 CASE 函数。
点击 关注 ,更新课程第一时间通知哦~
作者:喵宁一
游戏编程,一个游戏开发收藏夹~
如果图片长时间未显示,请使用Chrome内核浏览器。
边栏推荐
- Wireless communication module fixed-point transmission - point to multipoint specific transmission application
- 树莓派无需显示屏的VNC Viewer方式的远程连接
- 实体转JSON时,值为null的字段的丢失问题
- MytipartFile与File的相互转换
- 一种跳板机的实现思路
- [practice] 1364- implement a perfect waterfall flow component on the mobile terminal (with source code)
- Yann Lecun's new paper: the road to building automatic agents
- Wireshark数据抓包分析之FTP协议
- mysql数据库概述以及安装过程
- [leetcode daily question] [December 19, 2021] 997 Find the town judge
猜你喜欢

Internet of things application case of wireless module transparent transmission technology

Move command

利用soapUI获取freemarker的ftl文件模板

Information hidden in the trend chart of Hong Kong London gold market

Blue Bridge Cup Maze (dfs+ backtracking)

MarkDown——基本使用语法

MySQL (I)

AGCO AI frontier promotion (6.28)

Katalon框架测试web(二十)自定义关键字以及上传弹窗操作

How to use K-line diagram for technical analysis
随机推荐
Katalon框架测试web(二十)自定义关键字以及上传弹窗操作
An idea plug-in that automatically generates unit tests, which improves the development efficiency by more than 70%!
[practice] appium settings app is not running after 5000ms
Internet of things application case of wireless module transparent transmission technology
选择哪种编程语言,会吸引优秀的人才?
方法重写(Override)
Convert the file URL in the browser to a file stream
vsftpd服务的部署及优化
AGCO AI frontier promotion (6.28)
Docker modifies the user name and password of MySQL
Secretary of the Ukrainian national security and National Defense Commission: will carry out precision strikes against targets in Russia
MySQL查看数据库性能常用命令
How does ETF position affect spot gold price?
Move command
Summary of spatial temporal time series prediction modeling methods
Redis数据库
Compareto() and equals() methods of BigDecimal class
DataEase安装升级
fastposter v2.8.4 发布 电商海报生成器
Mongo database