SQL Server T—SQL 语句【查】

本文详细介绍了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 表名     --查最小值

 

转载于:https://www.cnblogs.com/Tanghongchang/p/6531393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值