Sql Server子查詢、GROUP BY分組、having查詢

1.子查詢
語法:select ... from 表1 where 字段1 > (子查詢語句)
例句
:查看年齡比“李斯文”大的學員,要求顯示學員信息;
select * from stuinfo where stuage > (select stuage from stuinfo where stuname = '李斯文')
實戰:查詢北京市下面的所有地區
select name from area where cityid = (select code from city where name = '北京市')
--注意:將“子查詢”和“比較運算”符聯合使用,必須保證子查詢返回的值不能多餘一個
----------------------------------------------------------------------------------------------------------------------
2.BETWEEN在某個範圍內進行查詢

語法:select ... from 表1 where 字段 between 參數1 and 參數2
select * from area where id between 1 and 20
GO
select * from area where id not between 10 and 20
----------------------------------------------------------------------------------------------------------------------
3.IN和NOT IN 子查詢
select * from area where cityid in('110100','130100')
GO
select * from area where cityid in (select code from city where code = '110100')
GO
select * from area where cityid not in(select code from city where code = '110100')
----------------------------------------------------------------------------------------------------------------------
4.GROUP BY分組查詢
select provinceid,avg(id) from city group by provinceid
GO
select provinceid,code from city group by provinceid,code
--注意:在使用Group By關鍵字時,在select列表中可以指定的項目是有限制的,
--1)被分組的列
--2)每個分組返回一個值的表達式,例如一個列名作爲參數的聚合函數(sum()、avg()、max()、min()、count())。
----------------------------------------------------------------------------------------------------------------------
5.HAVING子句分組篩選
select provinceid from city group by provinceid having count(*)>0
----------------------------------------------------------------------------------------------------------------------
注意:WHERE————》GROUP BY————》HAVING次序
select 部門編號,count(*) from 表
where 工資 >= 2000
group by 部門編號
having count(*)>1
----------------------------------------------------------------------------------------------------------------------
6.distinct去除重複
select name, distinct cityid from area

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章