欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQLServer--数据查询--子查询语法 博客分类: sql  

程序员文章站 2024-03-21 08:15:10
...

——————————子查询—————————————-

———–将查询的结果作为子表,连表查询 
select * from StuInfo s1,(select * from StuMarks where Score >80)s2 where s1.StuID=s2.StuID AND s1.StuName=’李四’

———–将查询结果作为条件使用 
select * from StuInfo WHERE StuID>(select StuID from StuInfo where StuName=’王五’) 
———–将子查询作为临时表使用 
select s1.,s2 Score from StuInfo s1 left outer join (select from StuMarks where Subject=’HTML’) s2 on s1.StuID=s2.StuID 
———–将子查询作为列使用 (不建议使用) 
select s1.*,(select Score from StuMarks s2 where s1.StuID=s1.StuID and subject=’html’) Score from StuInfo s1 
———–使用in 和not in 完成子查询 
select StuName from StuInfo where StuID In (select StuID from StuMarks where Score >85 and Subject=’java’) 
———–使用exist 或not exist 完成子查询 
select * from StuInfo where exists (select * from StuMarks where StuMarks.StuID=StuInfo.StuID) 
———–使用some 、any、 all进行子查询 
——————–聚合函数—————————————————– 
—————使用compute 和compute by进行汇总 
———————-排序函数 
—————排序函数over([分组子句]排序子句[desc][asc]) 
—————排序子句order by 排序列,排序列……. 
—————分组排序 partition by 分组列,分组列

————————row__number()函数 
select row_number() over (order by Score DESC) AS 排名 
s1.StuName,s2.Score from StuInfo s1,StuMarks s2 where s1.StuID=s2.StuID and s2.Subject=’Java’

————————rank函数 
select rank() over (order by Score DESC) AS 排名 
s1.StuName,s2.Score from StuInfo s1,StuMarks s2 where s1.StuID=s2.StuID and s2.Subject=’Java’

————————DENSE_RANK()函数 
select dense_rank() over (order by Score DESC) AS 排名 
s1.StuName,s2.Score from StuInfo s1,StuMarks s2 where s1.StuID=s2.StuID and s2.Subject=’Java’ 
————————-使用partition by 分组子句 
select dense_rank() over (partition by s2.Subject order by Score DESC) AS 排名 
s1.StuName,s2.Subject,s2.Score from StuInfo s1,StuMarks s2 where s1.StuID=s2.StuID 
————————-公用表达式 
————–CTE的基本用法 
WITH expression_name[(column_name[,…n])] 
as 
(CTE_query_definition)

with StuInfo_Mark (StuID,StuName,Subject,Score) 
as 

select s1.StuID,s1.StuName,s2.Subject, 
s2.Score from StuInfo s1,StuMarks s2 
where s1.StuID=s2.StuID 

select * from StuInfo_Mark 
go 
———————-2016.8.15

转自:http://blog.csdn.net/wx11055/article/details/52549484