SQL Server单表数据查询举例详解
时间:2023-10-27来源:系统城装机大师作者:佚名
一、向SQL Server中导入数据









导入成功之后,可以点开表格查看内容:
(如下图即导入成功)
其他表同理可得,也可以同时导入

二、例题
1.查询所有学生的全部信息

2.查询学生的学号和姓名
1 |
SELECT sno,sname FROM student |

3.查询所有学生的姓名和出生年
1 |
SELECT sname, YEAR (GETDATE())-sageFROM student |

4. 查询所有学生的姓名和出生年,要求列名是汉字形式
1 |
SELECT sname 姓名, YEAR (GETDATE())-sage 出生年 FROM student |

5.查询CS系的所有学生信息
1 |
select * FROM student WHERE sdept= 'CS' |

6.查询CS系的所有男同学信息
1 |
select * FROM student WHERE sdept= 'CS' AND ssex= '男' |

7.查询年龄在18到20之间的学生信息
(1)方法一
1 |
select * from student where sage>=18 and sage<=20 |

(2)方法二
1 |
select * from student where sage BETWEEN '18' AND '20' |

8.查询年龄不在18到20之间的学生信息
(1)方法一
1 |
select * from student where sage<18 or sage>20 |

(2)方法二
1 |
select * from student where sage not BETWEEN '18' AND '20' |

9.查询所在系为CS和JD的学生信息
(1)方法一
1 |
select * from student where sdept= 'CS' or sdept= 'JD' |

(2)方法二
1 |
select * from student where sdept in ( 'CS' , 'JD' ) |

10.查询姓张的学生的信息
1 |
select * from student where sname like '张%' |

11.查询姓名只有两个字且姓李的学生的学号和姓名
1 |
select sno,sname from student WHERE sname LIKE '李_' ; |

12.查询没有成绩的学生的学号和课程号
1 |
select * from sc WHERE grade IS NULL ; |

13.消除重复行:查看CS系的年龄情况
1 |
select DISTINCT sage FROM student WHERE sdept= 'cs' |

14.查询前三个同学的信息
1 |
select TOP 3 * from student |

15.统计男学生人数
(1)方法一
1 |
select COUNT (sno) 男生人数 from student where ssex= '男' |

(2)方法二
1 |
select COUNT (*) AS 男生人数 from student where ssex= '男' |

16.统计sc表中选修过课程的学生人数(注意要去掉重复选课的学生的学号)
1 |
select COUNT ( distinct sno) from sc |

17.从表sc中查询所有成绩中的最高分和最低分
1 |
select max (grade) 最高分, MIN (grade) 最低分 from sc |

18.统计学号为1204304102的学生的总成绩和平均成绩
1 |
select SUM (grade) 总分, AVG (grade) 平均分 from sc where sno= '1204304102' |

三、小结
(1) 有三种方法可以指定列名
- I. 列名 列标题(例如:sname 姓名)
- II. 列名 AS 列标题(例如:sname AS 姓名)
- III.列标题=列名(例如:姓名=列标题)
1 |
select sname 姓名, YEAR (GETDATE())-sage as 出生年,院系=sdept from student |

(2)根据名字的信息查询题目类总结
查询姓张的学生的信息
1 |
select * from student where sname like '张%' |
查询姓黄的学生的信息(当姓氏后面只有一个字时)
1 |
select * from student where sname like '黄_' |
查询名字中有“文”这个字的学生的信息
1 |
select * from student where sname like '_文_' |
(3)查询知识拓展
查询前三个同学的信息
1 |
select TOP 3 * from student |
查询课程编号是‘2102’的课程分数降序排列
1 |
select grade from sc where cno= '2102' order by grade desc |
查询课程编号是‘2102’的课程分数降序排列的前两名
1 |
select TOP 2 grade from sc where cno= '2102' order by grade desc |
总结
到此这篇关于SQL Server单表数据查询的文章就介绍到这了
相关信息
-
SQL Server 数据库中的收缩数据库和文件操作
收缩数据文件通过将数据页从文件末尾移动到更靠近文件开头的未占用的空间来恢复空间,在文件末尾创建足够的空间后,可取消对文件末尾的数据页的分配并将它们返回给文件系统,本文给大家介绍SQL Server 数据库中的收缩数据...
2023-10-27
-