SQL Server基础 SQL语句【查】

  查询数据(关键字:select)

1、简单查询       

     select * from 表名                    ——查全表

               select 列名 from 表名

               select 列名 as 别名 from 表名     —— as 起别名

2、条件查询 (where  or  and)

               select * from 表名 where 条件1                     ——查行

               select * from 表名 where   条件1   or /and    条件2

               select  列名  from 表名                                  ——查列

               select   列名1,列名2   from 表名 where 条件

3、模糊查询  ( like   %通配符  )

             select * from 表名 where 列名 like  ‘%字符%’                 // ' A%' 表示以A开头

4、排序查询 ( order by    desc降序   asc升序)

              select * from 表名 order by 列名  asc    ——升序            //  一般默认升序

              select * from 表名 order by 列名 desc   ——降序             // 升降序不是查询条件,不对查询产生影响 不用and连接直接写在最后

5、去重查询  ( distinct )                                            

            select distinct  列名  from  表名                                       //只允许查一列,查一列去重显示

6、分组查询  (group by     having)

            select  列名 from 表名 group by 列名                                //前后列名相对应

            select * from 表名 group by 列名 having  条件                   //having需要跟在group by 后使用

7、子查询

一条SQL语句中包含两个查询,其中一个是父查询(外层查询),另一个是子查询(里层查询),子查询查询的结果作为父查询的条件。

子查询可以单独执行,

子查询必须是一列,可以是多行

//查询系列是宝马5系的所有汽车信息
 select * from Car where Brand =(select Brand_Code from Brand where Brand_Name = '宝马5系')

①  in   /   not in                                     ——子查询的结果是多个时使用

                      父查询  in / not in  (子查询) 

②  any                                                   —— 任意  大于最小的,小于最大的

                     父查询 > any  (子查询)

③ all                                                        —— 所有 大于最大的 ,小于最小的

                      父查询 > all  (子查询)

④ between  and                                      —— 表示范围

                         select * from 表名 where 列名 between 值1 and 值2

8、分页查询  (top  n 取前n个值)

             select  top n * from 表名

9、聚合函数(统计函数)

             select count(*) from 表名      --查个数

             select sum(列名) from 表名    --查和

             select avg(列名) from 表名     --查平均数

             select max(列名) from 表名    --查最大值

             select min(列名) from 表名     --查最小值

10、查询前几行

  select  top 1  *  from  student ; 

                                      —— 查询全部取第一行

  select  top  2  *  from  student ; 

                                     —— 查询全部取前两行

  select  top 1 * from student  where  ids  not  in (  select  top 1  ids  from  student   )

                                      —— 查询第二行  括号内1变为 2 取第三行

原文地址:https://www.cnblogs.com/Tanghongchang/p/6531393.html