常用SQL語句的整理--SQL server 2008(查詢二--)

來源:互聯網
上載者:User

標籤:

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(查詢二--)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.