sql server基础查询

本文介绍了使用SQL创建数据库及表、插入数据的基本方法,并详细展示了如何进行数据查询,包括条件筛选、排序、分组等高级操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

```
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的所有字符串那一行

“`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值