数据分析之SQL常问知识点

本文深入探讨SQL常用操作,包括INSERT INTO SELECT与SELECT INTO FROM语句的差异,表添加默认值的方法,用一张表更新另一张表记录的技巧,多表行数据的纵向组合显示,COUNT与DISTINCT的使用细节,DELETE与TRUNCATE的区别,以及不使用排名函数求排名前两名的值等实战技巧。

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

数据分析之SQL常问知识点
一:Insert into select 语句 与 select into from 语句

语句形式:

Insert into Table2(field1,field2,...)
select value1,value2,value3,...from Table1

要求目标表Table2 必须存在,由于目标Table2 已经存在,所以我们除了插入源表Table1 的字段外,还可以插入常量。

语句形式为:

select value1,value2 into Table2 from Table1 

要求目标Table2 不存在,因为在插入的时候会自动创建表Table2,并将Table1 中指定字段数据复制到Table2中。

二:表添加默认值
create table student(
    stuId int identity(1,1) primary key,--加入主键
    stuName varchar(10) unique not null,--加入唯一约束
    stuAge int Check(stuAge between 18 and 100),--加入检查约束大于=18,小于=100就好。
    stuAddress varchar(20) default 'china',--加入默认约束   
    stuDel varchar(20)
)
三:用一张表的记录去更新另一张表的记录
update A
set A.Name=B.Name
set A.Sex=B.Sex
from A,B
where
A.ID=B.ID
四:将多表中的行纵向组合显示

将多表中的行纵向组合显示,当然要显示的列的属性每个表的定义都要一样,比如都是字符型的,顺序和个数也要一样。

    select UserName from A
    union all
    select username from B

union all将显示结果中的原始值
union 就是想显示结果加一个distinct,显示的结果没有重复的值,建议用union all
UNION的结果集列名与第一个select语句中的结果集中的列名相同,其他select语句的结果集列名被忽略

五:有关count 的小知识点

count()获取的是行数,
假设某一行全是NULL,那么count(
)能累加到这行,但是若是Count(列名),则不累加这行,所以聚集函数会忽略NULL的

六:distinct 的小知识点

distinct的用法,只能用一次,且在最前面,去除重复的行,而不是去除重复的列

七:Delete和Truncate的区别

Delte 删除的时候记录日志,而truncate 不记录日志。

八:不使用排名函数,求排名前两名的值
create table tb(id int,iorder int)
insert into tb
select 1,2 union all
select 1,3 union all
select 1,6 union all
select 1,6 union all
select 2,3 union all
select 2,1 union all
select 2,4
go

select *
from tb t
where (select count(*) from tb where id = t.id and iorder <= t.iorder) > 2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值