SQL Server中資料檢索(簡單查詢)

2021-05-25 16:54:17 字數 3907 閱讀 9923

1.選擇列

1)select 列名1,列名2...

from 表名

select sno,sname

from student

2)所有列

select *

from 表名

3)計算列

select sno,grade+2 'newgrade'

from sc

select productid,price*stocks

from products

select rtrim()sname+'是'+rtrim(s***)+'生'

from student

擷取空格的函式

rtrim()

4)增加列標題

『列標題』=列名

列名 [as] 『列標題』

select '學號'=sno,sname as '姓名'

from student

2.選擇行

select...

from...

where...

1)比較運算子

>,<,<>,!=,...

select sno,grade

from sc

where grade>80

select *

from student

where s***='男'

select *

from student

where year(sbrithday)=1991

select *

from student

where year(getdate())-year(sbrithday)>20

select year(sbrithday),sname

from student

2)邏輯運算子

not,and,or

not>and>or

select *

from sc

where cno='c101' and grade>80

select*

from sc

where cno='c101' and(grade>80 or grade<60)

select*

from sc

where cno='c102' and (grade<60 or grade is null)

補充:null 不確定

is null 比較某一列是否為空

3.查詢範圍

間斷in(...)  x in(a,b)===x=a or x=b

not in(a,b)===x!=a and x!=b

連續between..and...  x between a and b ====

select*

from sc

where grade between 80 and 100

select *

from sc

where cno in('c101','c103','c105')

select productname,productid

from products

where  price*stocks between 50 and 1000

select *

from products

where price>50 or stocks<100

select *

from products

where price is null

4.模糊查詢 like

% _ [^](四個佔位符)

select *

from student

where sname like '李%'

select *

from student

where sname like '%偉%'

select *

from student

where sname like '_偉%'

select*

from student

where sname like '%偉'

select *

from student

where sname  not like'%偉%'

select *

from student

where sname not like '_偉%'

或者select *

from student

where sname like '_[^偉]%'

select *

from student

where rtrim(sname) like '李_'

select *

from student

where rtrim(sname) like '[李、張]_ '

5.

1).消除重複值 distinct

select distinct cno

from sc

where grade<60 or grade is null

2).top n,top n percent

select top 3*

from student

select top 10 percent *

from student

3).order by 列名 asc(公升序)|desc(降序),(如果沒寫的情況下預設為asc)

select *

from sc

order by grade desc

select top 3 *

from sc

where cno='c101'

order by grade desc

練習

1查詢products表中總價量最高的5種產品名字

2查詢products表中單價在20~40之間的產品資訊

3查詢products表中三個字的產品有哪些

select top 5 productname

from products

order by price*stocks desc

select*

from products

where price between 20 and 40

select *

from products

where rtrim (productname) like '___'

SQLServer基礎的資料檢索

use 公司 select from 員工 select 性別,生日 from 員工 select 性別 as gender,as前面為原本列名,後面為新列名 生日 birthday,空格用法與as類似 name 姓名 用法有點類似變數賦值,前面為新列名,後面為原有列 from 員工 select ...

Data Retrieval 資料檢索

index 索引 定義 分類 1 結構化資料 固定格式 有限長度 應用 資料庫 元資料 2 非結構化資料 非定格式 非限長度 應用 磁碟檔案 查詢方式 1 結構化查詢 資料庫搜尋 2 非結構化查詢 a 順序掃瞄 b 全文檢索定義 根據使用者需求,從資料庫提取資料,生成資料表。資料表 可放回資料庫,也...

基本資料檢索

2016.11.28 二 基本資料檢索 select from table select 和 from 號是特殊符號,它表示所有的列,這句話的意思就是從 table 中查詢所有的列。在mysql和 oracle 中要求每句話的末尾要加乙個分號 但在 sqlserver 中不適用。2.1 查詢指定列 ...