SQL Server查詢語句


1.查詢第二個字母是t或者a的雇員的全部信息

1 select *
2 from employees
3 where firstname like '_[t,a]%'

注意:在sql中%表示字符串,所以不可像matlab一樣用其注釋,兩個雙斜線好像也不行,/**/可以,有網友說sql單行注釋為--

2.更改字段名

1 select '名字' = firstname ,'姓氏' = lastname
2 from employees 
3 where firstname like '_[t,a]%'

或者

1 select  firstname as '名字' , lastname as '姓氏'
2 from employees 
3 where firstname like '_[t,a]%'

3.top關鍵字

1 /*檢索出符合條件的前70%條記錄*/
2 select  top 70 percent firstname as '名字' , lastname as '姓氏'
3 from employees 
4 where firstname like '_[t,a]%'
1 /*檢索出符合條件的前2條記錄*/
2 select  top 2 firstname as '名字' , lastname as '姓氏'
3 from employees 
4 where firstname like '_[t,a]%'

4.union關鍵字
注意:標准sql只提供了並操作,未提供交(intersection)和差(minus)操作。

1 select *
2 from employees
3 where title = 'Sales Manager'
4 union 
5 select *
6 from employees
7 where address is not null

顯示:

服務器: 消息 8163,級別 16,狀態 4,行 1
不能以 DISTINCT 方式選擇 text、ntext 或 image 數據類型。

1 select *
2 from employees
3 where title = 'Sales Manager'
4 union all
5 select *
6 from employees
7 where address is not null

查詢分析其中的分析查詢(對號)是看下是否有語法錯誤(ctrl + F5),執行查詢(右三角)(F5)是顯示結果的若有語法錯誤則不執行。

5.compute關鍵字

compute子句需要以下信息:
1. 可選的By關鍵字可按對一列計算指定的行聚合
2. 行聚合函數:sum,avg,min,max,count
3. 要對其執行行聚合函數的列
當compute帶有可選的By子句時,符合select條件的每個組都有兩個結果集:
1. 每個組的第一個結果集是明細行集,其中包含該組的選擇列表信息
2. 每個組的第二個結果集有一行,其中包含該組COMPUTE子句中所指定的聚合函數的小記

1 select sex,sclass,score 
2 from student 
3 order by sex 
4 compute sum(score) by sex 

注意:order by是必須的,並且 compute by后的參數應該在order by后的參數中出現過

1 select sex,sclass,score 
2 from student 
3 compute sum(score) 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM