SQLServer条件查询,排序

本文介绍了SQL中的基本运算符,如比较运算符、逻辑运算符和模糊查询,以及如何进行指定条件查询(包括多条件、范围、IN和CASE语句)、排序(升序和降序)以及常用的函数如LEN、YEAR、MONTH和DAY。
摘要由CSDN通过智能技术生成

一.常用的运算符

=:相等

!=:不等

>:大于

<:小于

>=:大于等于

<=:小于等于

IS NULL:为空

IS NOT NULL:不为空

in:在其中

like:模糊查询

BETWEEN...AND...:在两个条件之间

and:逻辑与

or:逻辑或

not:逻辑非

CASE

        WHEN 判断条件 then 写入条件

END

二.查询

1.指定条件查询

格式:SELECT 查询列(可查询复数个) from 表名 WHERE 判断条件

例如我要查询Student表中Score大于90的数据

SELECT Id,Score from WHERE Score > 90

2.指定条件查询(多条件)

(1).使用and添加条件

格式:

SELECT 查询列 from 表名 判断条件1 and 判断条件2(可以使用复数个判断条件)

例如我要查询Student表中Score大于90并且Address为成都的数据

SELECT Score,Address WHERE Score > 90 and Address = '成都'

(2).使用between...and...判断在一个范围中的数据

格式:

SELECT 查询列 from 表名 WHERE 判断条件 BETWEEN ... AND ...

例如我要查询Student表中Score在80到90之间的数据

SELECT Score from Student WHERE Score BETWEEN 80 AND 90

(3).使用in查询

格式:

SELECT 查询列 from 表名 WHERE 判断条件

例如我要查询Student表中Address为成都和重庆的数据

SELECT Address from Student WHERE Address in('成都','重庆')

(4).使用when then语句

查询学生的生肖

SELECT * 
case
    when year(Birth) % 12 = 4 then '鼠'
    when year(Birth) % 12 = 5 then '牛'
    when year(Birth) % 12 = 6 then '虎'
    when year(Birth) % 12 = 7 then '兔'
    when year(Birth) % 12 = 8 then '龙'
    when year(Birth) % 12 = 9 then '蛇'
    when year(Birth) % 12 = 10 then '马'
    when year(Birth) % 12 = 11 then '羊'
    when year(Birth) % 12 = 0 then '猴'
    when year(Birth) % 12 = 1 then '鸡'
    when year(Birth) % 12 = 2 then '狗'
    when year(Birth) % 12 = 3 then '猪'
    else ''--如果不属于其中的任何一个表示数据有错误,直接添加一个空字符串报错
end 生肖--自定义中文列名为生肖
from People

简写方式:

SELECT * 
case year(Birth) % 12
    when 4 then '鼠'
    when 5 then '牛'
    when 6 then '虎'
    when 7 then '兔'
    when 8 then '龙'
    when 9 then '蛇'
    when 10 then '马'
    when 11 then '羊'
    when 0 then '猴'
    when 1 then '鸡'
    when 2 then '狗'
    when 3 then '猪'
    else ''--如果不属于其中的任何一个表示数据有错误,直接添加一个空字符串报错
end 生肖--自定义中文列名为生肖
from People

三.排序

desc:降序排列方式

asc:升序排列方式

1.根据条件排序

格式:

SELECT 列名 from 表名 order by 条件列 排序方式

例如我要查询Student表中Score按照降序排列方式排列的数据

SELECT * from Student order by Score desc

四.常用于排序的函数

len()用于计算字符串长度

year()用于获取数据中的年份

getdate()用于获取当前时间

month():用于获取数据中的月份

day():用于获取数据中的日期

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值