--查看表中数据
select * from stuInfo;
select * from stuMarks;
--聚合函数的使用
select count(*) from stuInfo where stuSex='男';
select stuSex,count(*) as '男女的人数'from stuInfo group by stuSex;
--表关联操作
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo;
--查看年龄比“李斯文”大的学员
select * from stuInfo where stuAge>(select stuAge from stuInfo where stuName='李斯文');
--查看性别和“李斯文”一致的学员
select * from stuInfo where stuSex=(select stuSex from stuInfo where stuName='李斯文');
select stuSex from stuInfo where stuName='李斯文';
--查删除别和“李斯文”一致的学员
delete from stuInfo where stuSex =(select stuSex from stuInfo where stuName='李斯文');
--查询年龄最大的学生信息
select top 1 * from stuInfo order by stuAge desc;
select * from stuInfo where stuAge=(select max(stuAge) from stuInfo );
--查询年龄最小的学生信息
select * from stuInfo where stuAge=(select min(stuAge) from stuInfo );
--查询笔试成绩成绩最高的学生
select * from stuInfo where stuNo=(select top 1 stuNo from stuMarks order by writtenExam desc);
select top 1 a.stuNo,a.stuName,b.writtenExam from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo order by writtenExam desc;
--查询笔试成绩大于全班笔试平均成绩的学生记录
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo where writtenExam>(select avg(writtenExam) from stuMarks);
--查询笔试成绩在70分以上的学生信息(禁止联表)
select * from stuInfo where stuNo in(select stuNo from stuMarks where writtenExam>70);
--查看那些人没有考试
select * from stuInfo where stuNo not in (select stuNo from stuMarks);
select * from stuInfo a left join stuMarks b on a.stuNo=b.stuNo where writtenExam is null;
WFE_FlowRecord
表
中 WFE_FRCode为主键,WFE_PFRCode为父
表
的主键
现在想查询某个子
表
的所有父
表
的数据,且父
表
的标志位为WFE_FRSubFlow = 'F'
查询语句如下:
with cte AS
select WFE_PFRCode,WFE_FRSubFlow,WFE_FRCode,0 as lvl from WFE
--查询钱包里金额大于30000
select * from Users where exists (select User_ID from Wallets where Money > 30000 and User_ID = Users.ID)
select * from Users where ID in (select U...
SQL
Server
中的
子查询
是指在一个查询语句中嵌套
使用
另一个查询语句。
子查询
可以作为主查询的一部分,用于获取更具体的数据或进行进一步的筛选和计算。
下面是一个示例,展示如何在
SQL
Server
中
使用
子查询
:
```
sql
SELECT column1, column2
FROM table1
WHERE column1 IN (SELECT column1 FROM table2 WHERE column2 = 'value')
在上面的示例中,主查询从table1
表
中选择column1和column2列的数据。
子查询
被嵌套在WHERE子句中,用于从table2
表
中选择满足条件column2 = 'value'的column1列的数据。主查询将返回满足
子查询
条件的结果。
子查询
也可以用于其他操作,例如计算聚合
函数
、连接多个
表
等。在
使用
子查询
时,需要注意优化查询以提高性能,并确保正确
使用
子查询
的结果。
希望这个简单的示例对您有所帮助!如果您有更多关于
SQL
Server
子查询
的问题,请随时提问。