SQL Server T-SQL数据查询
SQL Server T-SQL数据查询SELECT查询语句
SELECT语句的语法格式
SELECT 列表达式
FROM 表名列表
]
SELECT子句投影查询
语法:SELECT 列名表达式1, 列名表达式2, …列名表达式n
其中:表达式中含列名、常量、运算符、列函数
1. 投影部分列
从securitycode表提取,所有股票的股票名称和股票代码
select symbol,sname from securitycode
2. TOP关键字限制返回行数
格式:TOP n
从securitycode表提取,前100条记录
select top 100 * from securitycode
3. 是否去重复元组
All:检出全部信息(默认)
Distinct:去掉重复信息
select distinctexchange from securitycode
4. 投影所有列
通配符*:所有字段
从securitycode表提取所有列
select * from securitycode
5. 自定义列名
格式:’指定的列标题’=列名
/ 列名 AS 指定的列标题
在上例中用中文显示列名。
select symbol as [股票代码],sname as [股票名称] from securitycode
6. 字段函数(列函数)
格式:函数名(列名)
求和:SUM
平均:AVG
最大:MAX
最小:MIN
统计:COUNT
从itprofile表提取 最大注册资本
select max(ITPROFILE21)from itprofile where ITPROFILE44=1
FROM子句连接查询
格式:FROM基本表名/视图,基本表名/视图,…
功能:提供基本表或视图的连接查询
7. 指定基本表或视图
use fcdb
go
select * from securitycode
8. 为基本表指定临时别名
格式:基本表名 别名
功能:简化表名,实现自连接。
select s.symbol,s.sname from securitycode s
WHERE子句选择查询
格式:WHERE逻辑表达式
功能:实现有条件的查询运算。
9. 比较运算符
=,,>,=,=开始值 and 列名='2005-01-01' and listdate140000.0000
查询结果:
ORDER BY排序查询
格式:ORDER BY 列名表达式表asc/ desc
功能:按列名表升序或降序排序。
说明:只能在外查询中使用。
select * from securitycode order by listdate
连接查询
连接方法和种类
SQL Server提供了不同的语法格式支持不同的连接方式。
15. 用于FROM子句的ANSI连接语法形式
SELECT 列名列表
FROM {表名1[连接类型] JOIN 表名2 ON 连接条件}
WHERE 逻辑表达式
16. 连接种类
内连接
交叉连接
外连接
内连接
格式:from 表名1 inner join 表名2 on 连接表达式
select a.symbol,a.sname,b.ITPROFILE7
from securitycode a
inner join
itprofileb
on a.companycode=b.companycode
外连接
17. 左外连接
格式:from 表名1 left outerjoin 表名2 on 连接表达式
加入表1没形成连接的元组,表2列为NULL。
select a.symbol,a.sname,b.ITPROFILE7
from securitycode a
left join
itprofileb
on a.companycode=b.companycode
18. 右外连接
格式:from 表名1 right outerjoin 表名2 on 连接表达式
加入表2没形成连接的元组,表1列为NULL。
select a.symbol,a.sname,b.ITPROFILE7
from securitycode a
right join
itprofileb
子查询
IN 子查询
(1)列名 in (常量表)|(子查询)
说明:列值被包含或不(not)被包含在集合中。
等价:列名=any(子查询)
select ITPROFILE7 from itprofile where COMPANYCODE in (select distinct companycode from securitycode where stype='EQA' and exchange='CNSESZ')
比较子查询
19. 列名 比较符 all (子查询)
说明:子查询中的每个值都满足比较条件。
select ITPROFILE7 from itprofile where COMPANYCODE =(select distinct companycode from securitycode where symbol='600000' and exchange='CNSESH')
联合查询
UNION操作符
格式:SELECT_1 UNION
SELECT_2 { UNION
SELECT_n
select companycode,announmt2,PublishDatefrom announmt where companycode='10000001'
union
select companycode,announmt2,PublishDatefrom announmt1 where companycode='10000001'
6.1.2 联合查询结果排序
select companycode,announmt2,PublishDatefrom announmt where companycode='10000001'
union
select companycode,announmt2,PublishDatefrom announmt1 where companycode='10000001' order by PublishDate desc
页:
[1]