您的位置:首页 > 数据库

SQL数据库基础之-查询语句(二)

2016-10-22 20:26 148 查看
-------------比较order by 与 compute by 区别-------------
select stu_xb,count(*)
from  dbo.Tb_Stu_Info
group by  stu_xb

select stu_name, stu_xb
from dbo.Tb_Stu_Info
order by stu_xb ,stu_name
compute count(stu_xb) by stu_xb--分类依据

select stu_name ,left(Stu_Address,2)
from dbo.Tb_Stu_Info
order by left(Stu_Address,2) , stu_name--简单汇总
--group by left(Stu_Address,2)
compute count(left(Stu_Address,2)) by  left(Stu_Address,2)--分类依据,汇总,具有明细

select stu_name,stu_xb
from dbo.Tb_Stu_Info where stu_xb='男'
union
select stu_name,stu_xb
from dbo.Tb_Stu_Info where stu_xb='女'

--语法上允许--
select top 6 stu_no, stu_name
from dbo.Tb_Stu_Info
union
select top 6 stu_xb,Stu_Address
from dbo.Tb_Stu_Info

--连接查询--
select * from  Tb_Stu_Score

select
a.stu_name,--如果将列的排列顺序改变,那么输出结果也会改变
-- b.subject_Id,
c.subject_name,
b.score
from Tb_Stu_Info a inner join  Tb_Stu_Score b
on a.stu_no=b.stu_no
inner join  Tb_Subject c
on  b.subject_id=c.subject_id

select
a.stu_name,--如果将列的排列顺序改变,那么输出结果也会改变
-- b.subject_Id,
b.score,
c.subject_name
from Tb_Stu_Info a inner join  Tb_Stu_Score b
on a.stu_no=b.stu_no
inner join  Tb_Subject c
on  b.subject_id=c.subject_id--公共列
--只显示表中可匹配的结果

--外连接--
--左外连接--
select
a.stu_name,--如果将列的排列顺序改变,那么输出结果也会改变
b.subject_Id,
b.score
from Tb_Stu_Info a  left outer join  Tb_Stu_Score b
on a.stu_no=b.stu_no
--右外连接--
select
a.stu_name,--如果将列的排列顺序改变,那么输出结果也会改变
b.subject_Id,
b.score
from Tb_Stu_Info a  right outer join  Tb_Stu_Score b
on a.stu_no=b.stu_no
--全外连接--
select
a.stu_name,--如果将列的排列顺序改变,那么输出结果也会改变
b.subject_Id,
b.score
from Tb_Stu_Info a   full outer join  Tb_Stu_Score b
on a.stu_no=b.stu_no

--子查询--
select score from  Tb_Stu_Score
where stu_no in(select stu_no from tb_stu_info
where Stu_Name='林于庭')
and subject_id='1'

select subject_id

--错误------------------------------------------------------------------
select Stu_Name from Tb_Stu_Info
where stu_no in(where subject_id=(select subject_id from  Tb_Subject
where subject_name='英语')
and score>=80)

select stu_no from   Tb_Stu_Info
where subject_id=(select subject_id from  Tb_Subject
where subject_name='英语')
and score>=80

select subject_id from  Tb_Subject
where subject_name='英语'

select score from Tb_Stu_Score
where score>80
and
--------------------------------------------------------------------

SELECT     Tb_Stu_Info.Stu_Name, Tb_Subject.subject_name, Tb_Stu_Score.score
FROM       Tb_Stu_Info INNER JOIN
Tb_Stu_Score ON Tb_Stu_Info.stu_no = Tb_Stu_Score.stu_no INNER JOIN
Tb_Subject ON Tb_Stu_Score.subject_id = Tb_Subject.subject_id

--内连接和子查询可以跨表查询--、

--exists的子查询--
select * from dbo.Tb_Stu_Info
where exists(select * from  Tb_Stu_Score
where score=80)
exists--是否存在相当于开关

--基于查询生成新表--

select * into male_Stu_Info from  Tb_Stu_Info
where Stu_xb='男'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息