sql server基础查询

```
create database stuinfo  
go
use stuinfo;

drop table student
CREATE TABLE student
(
    id  int     primary key identity(1,1),--建主键与默认值,默认为1每次加1,默认值默认为(1,1)
    name    varchar(50), --50个字节,不足50个自动去除多余的空间
    age int,
    sex     char(2)    --2字节,等于一汉字,不足2字节多余的一个字节显示空格,不自动去除
);


--插入数据
insert into student values('曹操',20,'男');
--批量插入
insert into student
select '张辽',20,'男' union
select '徐晃',20,'男' union
select '郭嘉',20,'男' union
select '曹仁',20,'男'
--批量插入
insert into student values
('孙权',21,'男'),
('周瑜',22,'男'),
('鲁肃',21,'男'),
('张郃',23,'男');

select top 13 * from student  --取得前三

select distinct sex from student  --去重显示

--求年龄的和、最小、平均、最大数、行数,
select SUM(age) as  '总和' from student 
select min(age) from student 
select avg(age) from student 
select max(age) from student 
select count(*) from student 

--age字段2021(包含)之间的数,intselect * from student where age between  20 and 21 

--包含2122的行
select * from student where age in(21,22)
select * from student where age not in(21)

--排序、倒叙
select * from student  order by age asc
select * from student  order by age desc

--分组
select max(name),age from student group by age

--分组之后倒叙
select max(name),age from student group by age order by age desc

--分组之后再筛选每个组内个数大于等于2个的
select max(name),age from student group by age  having count(*)>=2 
--分组之后再筛选每个组内最小数大于21的哪个组,再排序
select max(name),age from student group by age  having min(age)>21 order by age desc


select * from student where name like '%张%'  --包含 张 字
select * from student where name like '张%'  --以 张 字开头的字符
select * from student where name like '%张' --以 张 字结尾的字符

select * from student where age like '_1' --以1结尾的有两个字的那一行
select * from student where age like '2_' --以2开头的有两个字的那一行

select * from student where age like'[12]63[56]9'--搜索w表h列以1字或2字开头,接下来是63,第五个字母是56,第六个是9的那一行的所有列的信息
select * from student where age like'[1~9]55'--搜索w表h列以1~9任意单个字母开头,55结尾的那一行的所有列的信息
select * from student where age like'm[^2]%'--搜索w表h列以m字开头,第二个字母不是2的所有字符串那一行

“`

猜你喜欢

转载自blog.csdn.net/yh12346789/article/details/79842712