数据库常用操作命令
- 格式:docx
- 大小:162.64 KB
- 文档页数:5
1、插入
insert into tabe_name values(1,2,3,4,5,6,7)
2、更新
update tale_name set key='' where id=''
3、运算,根据生日,计算年龄
select stu_id,name,YEAR(getdate())-YEAR(birthday) from stu_data
4、还可以修改标题名字
select stu_id as'学号',name as'姓名',
YEAR(getdate())-YEAR(birthday)as'年龄'from stu_data
5、去除重复项
select distinct sdept from stu_data(查询sdept不同的项,方便看出有多少数量)6、返回部分数据
Select top 5 stu_id,name,mark from stu_data (查询ID前5个同学的信息)7、还可以按比例查询
Select top 60 percent stu_id,name,mark from stu_data(前60%的同学)
8、条件查询
select stu_id,name,mark from stu_data where mark> 570 (查询分数大于570分的同学)
select stu_id,name,mark from stu_data where mark> 570 and sex='男'(查询分数大于570分的“男”同学)
select stu_id,name,mark from stu_data where mark between 530 and 565
(查询分数在530-565的同学)
select stu_id,name,mark from stu_data where name like'张%'(查询所有姓张的同学)
select stu_id,name,mark from stu_data where name like'张_'(like模糊查询,查询所有“姓张”的同学,且姓名长度为2)
select stu_id,name,mark from stu_data where name like'[张王]%'(like 模糊查询,查询所有“姓张和王”的同学)
select stu_id,name,mark from stu_data where name like'[^张王]%'(like 模糊查询,查询所有“不姓”张和王的同学)
9、排序
asc|desc升序和降序
select*from stu_data where mark<565 order by mark asc
10、统计数量
select COUNT(*)as'人数'from stu_data
11、统计指定ID的同学的成绩统计情况,最高分,最低分、平均分
select MAX(grade)as'最高分',MIN(grade)as'最低分',AVG(grade)as'平均分',SUM(grade)as'总分'from stu_grade where stu_id='201407002'
12、统计每个同学的最高、低、平均分
select stu_id,MAX(grade)as'最高分',MIN(grade)as'最低分',AVG(grade)as'平均分',SUM(grade)as'总分'from stu_grade group by stu_id
13、大于80分的人才参与统计
select stu_id,MAX(grade)as'最高分',MIN(grade)as'最低分',AVG(grade)as'平均分',SUM(grade)as'总分'from stu_grade where grade>=80 group by stu_id
14、上一步中在筛选平均分大于85的
select stu_id,MAX(grade)as'最高分',MIN(grade)as'最低分',AVG(grade)as'平均分',SUM(grade)as'总分'from stu_grade where grade>=80 group by stu_id having avg(grade)>85
15、分组统计
select*from stu_data order by sdept compute count(stu_id)by sdept
16、查询2个数据库表中的关联数据
select stu_data.stu_id as'学号',stu_grade.course_id as'科目',name,mark from stu_data,stu_grade where stu_data.stu_id=stu_grade.stu_id and course_id='701'
17 、关联3张表
select stu_data.stu_id as'学号',course_name as'科目',grade as'成绩',name,mark from stu_data,stu_grade,course_info where stu_data.stu_id=stu_grade.stu_id and stu_grade.course_id='701'
19、给表定义别名,使用方便
select A.stu_id as'学号',course_name as'科目',grade as'成绩',name,mark from stu_data as A,stu_grade as B,course_info as C where A.stu_id=B.stu_id and B.course_id='701'
其中A代表stu_data,B代表stu_grade,C代表course_info,注意,如果一旦用了别名后,其他地方都需要使用别名
19 嵌套查询查询比201407001 年龄小的同学
select*from stu_data where birthday<(select birthday from stu_data where stu_id='201407001')
19、数据库移位
假如A表存在,
则 insert into A(a,b,c) (select a,b,c from B)
假如A表不存在,
select a,b,c into A from B
假如需要跨数据库库
insert into ADB.[dbo].A(a,b,c) (select a,b,c from BDB.[dbo].B)。