標籤:
SQL中的內建函數:
--彙總函式COUNT--查詢表中資料的條數
select COUNT(*) from person
select COUNT(*) from person where age in(18,19,20)--可以跟想要的上一節講的所有函數
--MIN,MAX,Avg,SUM
select MIN(age) from person
select max(age) from person
select avg(age) from person
select sum(age) from person
--資料分組---根據年齡分組,然後取出分組後的資料
select age,COUNT(*) from person group by age
註:如果所用欄位沒有出現在group by後面,是不能用帶select語句中使用的(但是彙總函式是可以的),我們來看兩個例子
select age,COUNT(*)as 數量,AVG(age) from person group by age
錯誤用法:select age,COUNT(*)as 數量,username from person group by age
---錯誤提示:挑選清單中的列 ‘person.username‘ 無效,因為該列沒有包含在彙總函式或 GROUP BY 子句中。
Having是對分組後資訊的過濾,能用的列和select中能用的列是一樣,關於having和where的區別,這裡暫時不深入去說了,但是要明白一點是,having不能代替where
select age,COUNT(*)as 數量 from person group by age having age>15
---根據年齡分組統計數量,並且選擇年齡大於15的組別
--去除重複資料
select distinct age from person
--聯合結果集(把查詢結果結合成為1個查詢結果)註:上下兩個查詢語句欄位必須一致(名字,類型,個數都必須一致)
select username,age from personunionselect username,age from student
註:union和union all 的區別。前者合并重複資料,後者不合并,由於union需要對資料進行掃描和對比,所以效率低,所以如果不是要合并資料的話,建議用union all
--查詢每一個人的姓名和年齡,並且計算年齡綜合,然後放置最後一列中
select username,age from person union allselect ‘合計‘,SUM(age)from person
常用SQL語句的整理--SQL server 2008(查詢二--)