zoukankan      html  css  js  c++  java
  • 6、SQL Server 数据查询

    一、使用SELECT检索数据

    数据查询是SQL语言的中心内容,SELECT 语句的作用是让数据库服务器根据客户要求检索出所需要的信息资料,并按照规定的格式进行整理,返回给客户端。

    SELECT 语句的基本结构

    复制代码
    [WITH<common_tale_expression>]
    SELECT select_list [INTO new_table_name]
    [FROM table_source][where search_condition]
    [GROUP BY group_by_expression]
    [HAVING search_condition]
    [ORDER BY order_expression [ ASC | DESC ]] 
    复制代码

    WITH子句

    WITH子句用于指定临时命名的结果集,这些结果集成为公用表表达式(CTE)。该表达式源自简单查询,并且在单条SELECCT、INSERT、UPDATE或DELETE语句的执行范围内定义。

    use web;
    with AgeReps(Age,AgeCount) AS ( select Age,count(*) from tt as AgeReports where age is not null group by age)
    select age,agecount from AgeReps 

    查询命名为AgeReps临时表中的年龄,年龄总数。 临时表中为年龄分组并显示年龄数量。

    SELECT ··· FROM 子句

    SELECT 表明要读取信息,FROM指定要从中获取数据的一个或多个表的名称。

    复制代码
    select * from tables /* *查询全部列 */
    select id,name from tables /* 查询指定列 */
    select tables.id,tables.name from tables /*还可以表.列名*/
    /*别名显示*/
    select tt.id ID,tt.name 名字,tt.sex 性别,tt.age 年龄 from tt
    select ID = tt.id , 名字 = tt.name from tt
    select tt.id as ID,tt.name as 名字,tt.sex as 性别,tt.age as 年龄 from tt
    复制代码

    INTO 子句

    将查询的结果插入到新表中

    select tt.id,tt.name,tt.age into newTable from tt

    WHERE 子句

    为搜索追加搜索条件

    1.逻辑运算符(NOT、AND、OR)

    1.1 NOT : 对布尔型输入取反,使用NOT返回不满足表达式的行。

    1.2 AND : 组合两个布尔表达式,当两个表达式均为true时返回true。

    1.3 OR : 将两个条件组合起来,当满足任意一条时为true。

    优先顺序是 NOT AND OR。

    select * from [user] where id=1 and name = 'a' or name='bc' and not name='d'

    2.比较运算符

    = (是否相等)、 <> (是否彼此不等)、 !=(是否彼此不等) 、 >(大于) 、 >=(大于且等于) 、 !>(不大于) 、 < (小于) 、 < = (小于等于) 、 ! < (不小于) 。

    select * from [user] where age > 24

    LIKE 关键字

    select * from tables where name like ' 王%' 查找王开头的。
    select * from tables where name like ' 王_' 查找王开头后面跟一个字的。
    select * from tables where name not like ' 王_' 查找不是王开头后面跟一个字的。
    select * from tables where age like ' 2[2-4]' 查找2后面跟2到4之间的。
    select * from tables where age like ' 2[^2-4]' 查找2后面不再2到4之间的。

    BETWEEN 关键字

    select * from tables where age between 22 and 24 查找22 到24之间的。
    select * from tables where age not between 22 and 24 查找不再22到24之间的。

    IS (NOT) NULL 关键字

    在where子句中不能使用比较运算符(=)来对空值进行判断,只能用IS NULL 来对空值进行查询。

    select * from tables where age is null 查询 age为空的。
    select * from tables where age is not null age 不为空的。

    IN 关键字

    使用IN关键字来指定搜索范围,是否与子查询或列表中的值相匹配。

    select * from tables where id in ('001','002','003') 查找id范围在001 002 003中的。
    select * from tables where id not in ('001','002','003') 查找id范围不在001 002 003中的。

    ALL、SOME、ANY 关键字

    ALL:比较标量值和单列集中的值,与比较运算符和子查询一起使用。>ALL标识大于条件的每一个值,大于最大值。

    select * from tt where age > all(select age from tt where age = 24) 查询大于all里面的查询值。

    SOME|ANY:比较标量值和单列集中的值,SOME 和 ANY 是等效的,与比较运算符和自查询一起使用。> ANY 表示至少大于条件的一个值,大于最小值。

    select * from tt where age > any(select age from tt where age = 24)

    EXISTS 关键字

    select id , name from [user] where exists (select null)

    GOUP BY 子句

    将按照一个或多个列或表达式的值将一组选定行组合成一个摘要行集,针对每一组返回一行,分组。

    select age from tt group by age

    HAVING 子句

    通常在GOURP BY 子句中使用,在分组中指定条件搜索。

    select age from tt group by age having age = 24

    ORDER BY 子句

    对搜索进行排序,除非同时指定了TOP ,否则ORDER BY 子句在视图、内敛函数、派生表和子查询中无效。

    select * from tables order by id desc, 按照ID 倒序排序。
    select * from tables order by id asc 按照ID 升序排序。

    COMPUTE 子句

    生成合计作为附加的汇总列出现在结果集的最后。当与BY 一起使用时,COMPUTE子句在结果集内生成控制中断和小计。可在统一查询内指定COMPUTE BY 和 COMPUTE。

    select * from tables order by sex compute avg(avg)。 按照性别分组查询,并将平均年龄显示最后。
    select * from tables order by sex compute avg(avg) by sex。 按照性别分组查询,并按照性别分开显示,显示出两组平均年龄。 

    ALL 关键字

    查询所有记录。

    select all age from tables

    DISTINCT 关键字

    去掉搜索结果中重复的记录。

    select distinct age from tables

    TOP 关键字

    限制查询结果显示的行数

    select top 5 * from tables.

    二、使用UNION合并多个查询结果

    表的合并操作将两个表的行合并到了一个表中,且不需要对这些行作任何更改。在构造合并查询时必须:

    1.两个select语句选择列表中的列数目必须一样多,而且对应位置上的列的数据类型必须相同或者兼容。

    2.列的名字或者别名是由第一个select语句的选择列决定的。

    3.可以为每个select 语句都增加一个表示行的数据来源的表达式。

    4.可以将合并操作作为select into命令的一部分使用,但是info关联必须放在第一个select语句中。

    5.合并操作默认情况下去除重复的行,如果希望返回重复的行需要使用 all 关键字。

    6.用对所有select 语句的合并操作结果进行排序的order by子句,必须放到最后一个select 后面,但排序列名必须是第一个select 选择列表中的列名。

    UNION 与 联接之间的区别

    在合并中,两个表源列的数量与数据类型必须相同,在联接中,一个表的行可能与另外一个表的行有很大区别。

    在合并中,行的最大数量是两个表的“和”。在联接中,行的最大数量使他们的“乘积”

    去重:select id,name from [user] union select id,title from work 结果为 id name 下面两个表的信息

    重复:select id,name from [user] union all select id,title from work 包含重复行

    排序:select id,name from [user] union all select id,title from work order by name desc 排序第一表中的列

    列数不同:select id,name,sex from [user] union all select id,title,null from work order by name desc 用NULL填充

    子查询

    子查询是一个嵌套在select、insert、update或delete语句或其他子查询中的查询,返回单个值。

    select * from tables where id not in (1,3,4)。

    嵌套查询

    嵌套查询是指将一个查询块嵌套在另一个查询块的where子句或having短语的条件中查询。

    复制代码
    select * from tables where id in (select typeid from type where id = 86) id范围在返回结果中
    select * from tables where id not in (select typeid from type where id=84) id范围不在返回结果中
    select * from tables where age < some(select avg(avg) from student) 年龄小于平均年龄
    select * from tables where age <> any(select avg(avg) from student) 年龄不等于平均年龄
    select * from tables where age <> all(select avg from student where age > 90) 年龄没有大于90的信息
    select * from tables where not exists (select id from user where tables.id = user.id) 查询id不相等的信息
    复制代码

    联接查询

    水平方向合并两个数据集合,产生一个新的结果集,联接条件可以在from或where子句中指定。

    内部联接

    内部联接是从结果中删除其他被联接表中没有匹配行的所有行,所以可能会丢失信息。

    select * from [user] inner join [work] on [user].id=work.id 查询两表ID相同的信息。

    外部联接

    1.左向外联接 left join

    如果左表中的某一行在右表中没有匹配行,则在关联的结果中,显示为空值。

    select * from [user] left join [work] on [user].id = work.id 显示所有user信息 若work没有对应信息显示为NULL

    2.右向外联接 right join

    与左联接相反,如果右表中的某一行在左表中没有匹配行,则显示为空值。

    select * from [user] right join [work] on [user].id = work.id 以work为主体 若user没有对应信息显示为NULL

    3.完整外联接 full join

    返回左表和右表的所有行,当某一行在另一个表中没有匹配行时,另一个表的选择列将包含空值。

    select * from [user] full join [work] on [user].id = work.id 显示左右全部信息,若没有就显示NULL

    交叉联接 cross join

    第一个表的行数乘以第二个表的行数等于结果集的大小

    select * from [user] cross join work 平均交叉互补 不显示NULL

    多表联接

    WHERE:select * from table1,table2,table3 where table1.id =table2.id and table2.id = table3.id
    FORM:select * from table1 join table2 join table3 on table1.id = table2 and table2.id = table3.id   

    三、使用CASE函数进行查询

    复制代码
    select 数字 = case /* 别名 */
        when id = 10 then '是1哦' /* 如果id=1 则输出 是1哦 */
        when id = 11 then '11哦'
        when id = 12 then '12哦'
        else '没有' /* 否则 输出 没有*/
        end from [user]
    /*修改*/
    update [user] set sex = case 
        when sex='n' then '男'
        when sex='a' then '女'
    end
    复制代码

    四、函数

    聚合函数

    复制代码
    count(*):返回行数。
    count(列名):返回某列的个数。
    avg(列名):返回某列的平均值。
    max(列名):返回某列的最大值。
    min(列名):返回某列的最小值。
    sum(列名):返回某列值的和。  
    复制代码

    开窗函数

    复制代码
    --使用聚合函数后,返回结果只能是一行
    --使用over() 可以将聚合函数扩展到所有行
    --语法 聚合函数() over()
    
    select avg(score) from student; --返回一条信息 平均分。
    
    select *,avg(score) over() from student; --返回所有数据最后加一列平均分
    复制代码

    日期时间函数

    复制代码
    select getDate(); 当前系统日期 
    select dateadd(day,3,getDate()); 加3天 
    select dateadd(year,3,getDate()); 加年
    select dateadd(hour,3,getDate()); 加小时
    select dateDiff(day,'2013-02-01',getDate());  返回相差天数
    select dateDiff(second,'2013-02-01',getDate()); 返回相差秒数
    select dateName(month,getDate());  返回当前月份
    select dateName(minute,getDate()); 返回当前分钟 
    select dateName(weekday,getDate()); 返回当前星期
    select day(getDate());  返回当前日期天数
    select month(getDate()); 返回当前日期月份
    select year(getDate()); 返回当前日期年份 
    复制代码

    数字函数

    复制代码
    select abd(); 绝对值 
    select pi(); 圆周率
    select power(2,3); 乘方 
    select rand(100),rand(50),rand(); 随机数
    select rand(rand(),3) 精确小数位
    select squage();平方
    select sqrt(); 平方根 
    复制代码

    字符串函数

    复制代码
    select ascii('a'); 返回ascii值 
    select charindex(); 返回字符串起始位置
    select unicode('a'); 返回unicode值 
    select 'a' + space(2) + 'b'; 输出空格 
    select difference('hello', 'helloWorld'); 比较字符串相同 
    select replace('abcedef', 'e', 'E'); 替换字符串
    select stuff('hello world', 3, 4, 'ABC'); 指定位置替换字符串 
    select replicate('abc#', 3); 重复字符串 次数 
    select subString('abc', 1, 1); 截取字符串 
    select len('abc'); 返回长度 
    select reverse('sqlServer'); 反转字符串 
    select left('leftString', 4); 取左边字符串 
    select right('leftString', 6); 取右边字符串
    select lower('aBc')  转换小写
    select upper('aBc') 转换大写
    select ltrim(' abc') 去除左空格
    select rtrim(' abc    ') 去除右空格 
    复制代码

    转换函数

    cast(数据 as 类型);
    convert(类型,数据); 
    select '123' + 123;--输出结果为246 数据库中以数字优先
    select '123' + cast(123 as varchar); --输出结果为123123 注意不可以nvarchar因为这个是固定长度的。
    select '123' + convert(varchar,123); --123123
  • 相关阅读:
    Django Admin Cookbook-27如何在Django Admin后台中添加基于日期的过滤
    Django Admin Cookbook-26如何禁用Django Admin后台分页
    Django Admin Cookbook-25如何在模型列表页上显示更多行
    Django Admin Cookbook-24如何从两个不同的模型创建一个Django Admin后台页面
    Django Admin Cookbook-23如何在Django admin中添加嵌套的内联
    Django Admin Cookbook-22如何将一对一关系添加为Admin内联字段
    Django Admin Cookbook-21如何从Django Admin后台一个页面同时编辑多个模型
    个人收集的一些Django基础及实战教程
    Django Admin Cookbook-20如何删除模型的“添加”/“删除”按钮
    操作系统 RR轮转调度算法(C++实现)
  • 原文地址:https://www.cnblogs.com/allen0/p/5115122.html
Copyright © 2011-2022 走看看