数据分析之SQL常问知识点

浏览: 949

数据分析之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(10unique not null,--加入唯一约束
    stuAge int Check(stuAge between 18 and 100),--加入检查约束大于=18,小于=100就好。
    stuAddress varchar(20default '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
推荐 0
本文由 DataFrog 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册