CSharp基础起步第十五期---SqlServer 基础04数据检索


1.数据检索

  1. 简单的数据检索 :SELECT * FROM Student

  2. 只检索需要的列 :SELECT sName FROM Student 、age FROM Student WHERE sSex=‘女’。

  3. 还可以检索不与任何表关联的数据:select 1+1;select getdate();

  4. 可以为列起别名


2.Top、distinct

  1. Top 获取前几条数据,top一般都与order by连用

  2. 获得年纪最小的5个学生           Select top 5 sName,sAge from student order by sAge

  3. 获得年纪最大的10%的学生(percent)

  4. distinct 去除重复数据:

  5.        select distinct sName from student

  6.        select distinct sName,sAge from student

  7.    disTINCT是对查询出的整个结果集进行数据重复处理的,而不是针对某一个


3.带条件的查询

  1. Select …from…where …

  2. 查询没有及格的学生的学号

  3. select studentId from score where english < 60      

  4. 查询年龄在20-30岁之间的男学生

  5. select sName,sAge,sSex from student where sAge >=20 and sAge <=30 and sSex ='男'


4.Between…and …在之间

  1. 查询年龄在20-30岁之间的男学生

  2. 查询math成绩在80-90分之间的所有学生

  3. 建议:使用between … and …。(闭区间)

  4. select sName,sSex from student where sAge between 20 and 30 and sSex ='男'



5.空值处理

  1. 数据库中,一个列如果没有指定值,那么值就为null,数据库中的null表示“不知道”,而不是表示没有。因此select null+1结果是null,因为“不知道”加1的结果还是“不知道”。

  2. select * from score where english = null ; 

  3. select * from score where english != null ;都没有任何返回结果,因为数据库也“不知道”。

  4. sql中使用is null、is not null来进行空值判断: select * from score where english is null ; select * from score where english is not null ;

  5. 函数ISNULL ( check_expression,replacement_value )


6.数据排序

  1. ORDER BY子句位于SELECT语句的末尾,它允许指定按照一个列或者多个列进行排序,还可以指定排序方式是升序(从小到大排列,ASC)还是降序(从大到小排列,DESC)。 

  2. 按照年龄升序排序所有学生信息的列表:SELECT * FROM  Student ORDER BY sAge ASC 

  3. 按照英语成绩从大到小排序,如果英语成绩相同则按照数学成绩从大到小排序 :SELECT * FROM  score ORDER BY english DESC,math DESC

  4. ORDER BY子句要放到WHERE子句之后 : SELECT * FROM  score where english>=60 and math>=60 ORDER BY english DESC,math DESC

  5. Order by 语句一般要放到所有语句的后面,就是先让其他语句进行筛选,全部筛选完成后,最后排序一下。

  6. (表中数据是集合,集合是没有顺序的。Order by 返回的数据是有顺序的,故此我们把order by 以后返回的数据集合叫“游标”。)



欢迎关注趣味CSharp,完整笔记与您分享~~~~~~~~

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...