SQL Server学习笔记【认识SQL Server查询及分组嵌套查询】

1.SQL 是一个标准 89 92 99三个版本
SQL语言的前身是IBM公司的SEOUEL语言

2.T-SQL 是微软在遵循SQL标准的基础上,有针对SQL Server的功能添加


注意:以下查询均基于学生表
student[表名]
id  stunumber name age sex phone email[字段]


SQL 查询
    1.select 基本结构
        select 查询什么,列筛选
        form 在哪个表查询,主要连接要查询的表名称,
             建议写表的全名,即[数据库].[表名]
        where 满足什么条件,行筛选


    2.select [列名1] as '[新列名1]',...,[列名i] as '[新列名i]'
    from [表名]
    where 条件(如:name='刘力铭')


    3.不等于的四种表达方式(name是字段名)
        1)where name!='刘力铭'
        2)where name<>'刘力铭'
        3)where name not in('刘力铭')
        4)where not name='刘力铭'


    4.介于两者之间(表示一个范围)
        1)where age <=60 and age >=20
        2)where age between 20 and 60
        3)where name between '程鹏' and '王成'
            因为默认是以字母顺序排序,所以在陈鹏和王成中间有其他记录


    5.空值(NULL和空值做运算还是NULL,比如25+NULL=NULL)
        where name is null


    6.去重复 distinct关键字
        select distinct name from student where age<30


    7.top关键字
        1)select top 5 name,age from student   选取数据表中前5行记录
        2)select top 20 percent name,age from student   选取数据表中前百分之二十行记录


    8.随机返回表中任意行记录  NewId()聚合函数
        select top 5 name,age from student order by NewId()   随机返回表中的5行记录


    9.选取表中的数据到插入到新的表中  into关键字
        1)select top 5 name,age into table1 from student order by newid()
            任意选取student表中的前5行记录插入到表table1中

        2)select name,age,sex,phone,email into table2 from student where 1<>1
            因为后面1<>1永远为假,因此此语句仅仅只是把student表结构复制到表table2中


    10.NOT; AND; OR 的优先级别
        在SQL语句中NOT级别最高,其次是AND,最后是OR,常用括号限定


    11.嵌套子查询,在from后面可以再跟一个嵌套子查询,如:
        select distinct name from student
        (
            select name from student where age>30
        )
        where name like '%刘%'


    12.通配符和[]
        %    替代一个或多个字符
        _(下划线) 仅替代一个字符
        [charlist]    字符列中任何单一字符
        [^charlist]或[!charlist]    不再字符列中的任何单一字符

        例如:查询手机号码是135或者134开头,倒数第四位是5或者4的学生姓名和学号
        select name,stunumber from student where phone like '13[45]%[45]___'

        查询手机号码是135或者134开头,倒数第四位不是5或者4的学生姓名和学号
        select name,stunumber from student where phone like '13[45]%[^45]___'


    13.排序 desc; asc
        desc表示逆序,asc表示顺序

        例如:对student表中按年龄升序排列,如果年龄一样则女生排在男生前面
        1)select stunumber,name,sex,age,phone,mail form student order by age asc,sex desc
        2)select * form student order by age asc,sex desc


    14.max聚合函数
        注意:聚合函数不能写在where子句中,否则会报错
        聚合函数常用在嵌套中,或order by字句中

        例如:查询年龄最大的学生(使用嵌套子查询)
        select * from student where age=
        (
            select max(age) from student
        )


    15.如果字符串中本身就包含了% 则需要使用转义字符 escape关键字
        如:select * from student where name like '%/%33' escape '/'


    16.常用聚合函数(通过这些函数,可以把多行记录变成一行记录,所及叫聚合)
        count:求所选记录的行数
        avg:求所选记录的平均值
        sum:为所选记录求和
        max:求所选记录的最大值
        min:求所选记录的最小值

猜你喜欢

转载自blog.csdn.net/heuguangxu/article/details/53770577