SQL Server SQL高等查詢語句小結。本站提示廣大學習愛好者:(SQL Server SQL高等查詢語句小結)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL Server SQL高等查詢語句小結正文
Ø 根本經常使用查詢
--select
select * from student;
--all 查詢一切
select all sex from student;
--distinct 過濾反復
select distinct sex from student;
--count 統計
select count(*) from student;
select count(sex) from student;
select count(distinct sex) from student;
--top 取前N筆記錄
select top 3 * from student;
--alias column name 列重定名
select id as 編號, name '稱號', sex 性別 from student;
--alias table name 表重定名
select id, name, s.id, s.name from student s;
--column 列運算
select (age + id) col from student;
select s.name + '-' + c.name from classes c, student s where s.cid = c.id;
--where 前提
select * from student where id = 2;
select * from student where id > 7;
select * from student where id < 3;
select * from student where id <> 3;
select * from student where id >= 3;
select * from student where id <= 5;
select * from student where id !> 3;
select * from student where id !< 5;
--and 而且
select * from student where id > 2 and sex = 1;
--or 或許
select * from student where id = 2 or sex = 1;
--between ... and ... 相當於而且
select * from student where id between 2 and 5;
select * from student where id not between 2 and 5;
--like 隱約查詢
select * from student where name like '%a%';
select * from student where name like '%[a][o]%';
select * from student where name not like '%a%';
select * from student where name like 'ja%';
select * from student where name not like '%[j,n]%';
select * from student where name like '%[j,n,a]%';
select * from student where name like '%[^ja,as,on]%';
select * from student where name like '%[ja_on]%';
--in 子查詢
select * from student where id in (1, 2);
--not in 不在個中
select * from student where id not in (1, 2);
--is null 是空
select * from student where age is null;
--is not null 不為空
select * from student where age is not null;
--order by 排序
select * from student order by name;
select * from student order by name desc;
select * from student order by name asc;
--group by 分組
依照年紀停止分組統計
select count(age), age from student group by age;
依照性別停止分組統計
select count(*), sex from student group by sex;
依照年紀和性別組合分組統計,並排序
select count(*), sex from student group by sex, age order by age;
依照性別分組,而且是id年夜於2的記載最初依照性別排序
select count(*), sex from student where id > 2 group by sex order by sex;
查詢id年夜於2的數據,並完成運算後的成果停止分組和排序
select count(*), (sex * id) new from student where id > 2 group by sex * id order by sex * id;
--group by all 一切分組
依照年紀分組,是一切的年紀
select count(*), age from student group by all age;
--having 分組過濾前提
依照年紀分組,過濾年紀為空的數據,而且統計分組的條數和實際年紀信息
select count(*), age from student group by age having age is not null;
依照年紀和cid組合分組,過濾前提是cid年夜於1的記載
select count(*), cid, sex from student group by cid, sex having cid > 1;
依照年紀分組,過濾前提是分組後的記載條數年夜於等於2
select count(*), age from student group by age having count(age) >= 2;
依照cid和性別組合分組,過濾前提是cid年夜於1,cid的最年夜值年夜於2
select count(*), cid, sex from student group by cid, sex having cid > 1 and max(cid) > 2;
Ø 嵌套子查詢
子查詢是一個嵌套在select、insert、update或delete語句或其他子查詢中的查詢。任何許可應用表達式的處所都可使用子查詢。子查詢也稱為外部查詢或外部選擇,而包括子查詢的語句同樣成為內部查詢或內部選擇。
# from (select … table)示例
將一個table的查詢成果當作一個新表停止查詢
select * from (
select id, name from student where sex = 1
) t where t.id > 2;
下面括號中的語句,就是子查詢語句(外部查詢)。在裡面的是內部查詢,個中內部查詢可以包括以下語句:
1、 包括慣例選擇列表組件的慣例select查詢
2、 包括一個或多個表或視圖稱號的慣例from語句
3、 可選的where子句
4、 可選的group by子句
5、 可選的having子句
# 示例
查詢班級信息,統計班級先生人生
select *, (select count(*) from student where cid = classes.id) as num
from classes order by num;
# in, not in子句查詢示例
查詢班級id年夜於小於的這些班級的先生信息
select * from student where cid in (
select id from classes where id > 2 and id < 4
);
查詢不是班的先生信息
select * from student where cid not in (
select id from classes where name = '2班'
)
in、not in 前面的子句前往的成果必需是一列,這一列的成果將會作為查詢前提對應後面的前提。如cid對應子句的id;
# exists和not exists子句查詢示例
查詢存在班級id為的先生信息
select * from student where exists (
select * from classes where id = student.cid and id = 3
);
查詢沒有分派班級的先生信息
select * from student where not exists (
select * from classes where id = student.cid
);
exists和not exists查詢須要外部查詢和內部查詢停止一個聯系關系的前提,假如沒有這個前提將是查詢到的一切信息。如:id等於student.id;
# some、any、all子句查詢示例
查詢班級的先生年紀年夜於班級的先生的年紀的信息
select * from student where cid = 5 and age > all (
select age from student where cid = 3
);
select * from student where cid = 5 and age > any (
select age from student where cid = 3
);
select * from student where cid = 5 and age > some (
select age from student where cid = 3
);
Ø 聚合查詢
1、 distinct去失落反復數據
select distinct sex from student;
select count(sex), count(distinct sex) from student;
2、 compute和compute by匯總查詢
對年紀年夜於的停止匯總
select age from student
where age > 20 order by age compute sum(age) by age;
對年紀年夜於的依照性別停止分組匯總年紀信息
select id, sex, age from student
where age > 20 order by sex, age compute sum(age) by sex;
依照年紀分組匯總
select age from student
where age > 20 order by age, id compute sum(age);
依照年紀分組,年紀匯總,id找最年夜值
select id, age from student
where age > 20 order by age compute sum(age), max(id);
compute停止匯總後面是查詢的成果,前面一條成果集就是匯總的信息。compute子句中可以添加多個匯總表達式,可以添加的信息以下:
a、 可選by症結字。它是每列盤算指定的行聚合
b、 行聚合函數稱號。包含sum、avg、min、max、count等
c、 要對其履行聚合函數的列
compute by合適做先分組後匯總的營業。compute by前面的列必定如果order by中湧現的列。
3、 cube匯總
cube匯總和compute後果相似,但語法較簡練,並且前往的是一個成果集。
select count(*), sex from student group by sex with cube;
select count(*), age, sum(age) from student where age is not null group by age with cube;
cube要聯合group by語句完成份組匯總
Ø 排序函數
排序在許多處所須要用到,須要對查詢成果停止排序而且給出序號。好比:
1、 對某張表停止排序,序號須要遞增不反復的
2、 對先生的成就停止排序,得知名次,名次可以並列,但名次的序號是持續遞增的
3、 在某些排序的情形下,須要跳空序號,固然是並列
根本語法
排序函數 over([分組語句] 排序子句[desc][asc])
排序子句 order by 列名, 列名
分組子句 partition by 分組列, 分組列
# row_number函數
依據排序子句給出遞增持續序號
依照稱號排序的次序遞增
select s.id, s.name, cid, c.name, row_number() over(order by c.name) as number
from student s, classes c where cid = c.id;
# rank函數函數
依據排序子句給出遞增的序號,然則存在並列而且跳空
次序遞增
select id, name, rank() over(order by cid) as rank from student;
跳過雷同遞增
select s.id, s.name, cid, c.name, rank() over(order by c.name) as rank
from student s, classes c where cid = c.id;
# dense_rank函數
依據排序子句給出遞增的序號,然則存在並列不跳空
不跳過,直接遞增
select s.id, s.name, cid, c.name, dense_rank() over(order by c.name) as dense
from student s, classes c where cid = c.id;
# partition by分組子句
可以完成對分組的數據停止增長排序,partition by可以與以上三個函數結合應用。
應用partition by依照班級稱號分組,先生id排序
select s.id, s.name, cid, c.name, row_number() over(partition by c.name order by s.id) as rank
from student s, classes c where cid = c.id;
select s.id, s.name, cid, c.name, rank() over(partition by c.name order by s.id) as rank
from student s, classes c where cid = c.id;
select s.id, s.name, cid, c.name, dense_rank() over(partition by c.name order by s.id) as rank
from student s, classes c where cid = c.id;
# ntile均勻排序函數
將要排序的數據停止等分,然後依照等分排序。ntile中的參數代表分紅若干等分。
select s.id, s.name, cid, c.name,
ntile(5) over(order by c.name) as ntile
from student s, classes c where cid = c.id;
Ø 聚集運算
操作兩組查詢成果,停止交集、並集、減集運算
1、 union和union all停止並集運算
--union 並集、不反復
select id, name from student where name like 'ja%'
union
select id, name from student where id = 4;
--並集、反復
select * from student where name like 'ja%'
union all
select * from student;
2、 intersect停止交集運算
--交集(雷同部門)
select * from student where name like 'ja%'
intersect
select * from student;
3、 except停止減集運算
--減集(除雷同部門)
select * from student where name like 'ja%'
except
select * from student where name like 'jas%';
Ø 公式表表達式
查詢表的時刻,有時刻中央表須要反復應用,這些子查詢被反復查詢挪用,不只效力低,並且可讀性低,晦氣於懂得。那末公式表表達式可以處理這個成績。
我們可以將公式表表達式(CET)視為暫時成果集,在select、insert、update、delete或是create view語句的履行規模內停止界說。
--表達式
with statNum(id, num) as
(
select cid, count(*)
from student
where id > 0
group by cid
)
select id, num from statNum order by id;
with statNum(id, num) as
(
select cid, count(*)
from student
where id > 0
group by cid
)
select max(id), avg(num) from statNum;
Ø 銜接查詢
1、 簡化銜接查詢
--簡化聯接查詢
select s.id, s.name, c.id, c.name from student s, classes c where s.cid = c.id;
2、 left join左銜接
--左銜接
select s.id, s.name, c.id, c.name from student s left join classes c on s.cid = c.id;
3、 right join右銜接
--右銜接
select s.id, s.name, c.id, c.name from student s right join classes c on s.cid = c.id;
4、 inner join內銜接
--內銜接
select s.id, s.name, c.id, c.name from student s inner join classes c on s.cid = c.id;
--inner可以省略
select s.id, s.name, c.id, c.name from student s join classes c on s.cid = c.id;
5、 cross join穿插銜接
--穿插聯接查詢,成果是一個笛卡兒乘積
select s.id, s.name, c.id, c.name from student s cross join classes c
--where s.cid = c.id;
6、 自銜接(統一張表停止銜接查詢)
--自銜接
select distinct s.* from student s, student s1 where s.id <> s1.id and s.sex = s1.sex;
Ø 函數
1、 聚合函數
max最年夜值、min最小值、count統計、avg均勻值、sum乞降、var求方差
select
max(age) max_age,
min(age) min_age,
count(age) count_age,
avg(age) avg_age,
sum(age) sum_age,
var(age) var_age
from student;
2、 日期時光函數
select dateAdd(day, 3, getDate());--加天
select dateAdd(year, 3, getDate());--加年
select dateAdd(hour, 3, getDate());--加小時
--前往跨兩個指定日期的日期界限數和時光界限數
select dateDiff(day, '2011-06-20', getDate());
--相差秒數
select dateDiff(second, '2011-06-22 11:00:00', getDate());
--相差小時數
select dateDiff(hour, '2011-06-22 10:00:00', getDate());
select dateName(month, getDate());--以後月份
select dateName(minute, getDate());--以後分鐘
select dateName(weekday, getDate());--以後禮拜
select datePart(month, getDate());--以後月份
select datePart(weekday, getDate());--以後禮拜
select datePart(second, getDate());--以後秒數
select day(getDate());--前往以後日期天數
select day('2011-06-30');--前往以後日期天數
select month(getDate());--前往以後日期月份
select month('2011-11-10');
select year(getDate());--前往以後日期年份
select year('2010-11-10');
select getDate();--以後體系日期
select getUTCDate();--utc日期
3、 數學函數
select pi();--PI函數
select rand(100), rand(50), rand(), rand();--隨機數
select round(rand(), 3), round(rand(100), 5);--准確小數位
--准確位數,正數表現小數點前
select round(123.456, 2), round(254.124, -2);
select round(123.4567, 1, 2);
4、 元數據
select col_name(object_id('student'), 1);--前往列名
select col_name(object_id('student'), 2);
--該列數據類型長度
select col_length('student', col_name(object_id('student'), 2));
--該列數據類型長度
select col_length('student', col_name(object_id('student'), 1));
--前往類型稱號、類型id
select type_name(type_id('varchar')), type_id('varchar');
--前往列類型長度
select columnProperty(object_id('student'), 'name', 'PRECISION');
--前往列地點索引地位
select columnProperty(object_id('student'), 'sex', 'ColumnId');
5、 字符串函數
select ascii('a');--字符轉換ascii值
select ascii('A');
select char(97);--ascii值轉換字符
select char(65);
select nchar(65);
select nchar(45231);
select nchar(32993);--unicode轉換字符
select unicode('A'), unicode('中');--前往unicode編碼值
select soundex('hello'), soundex('world'), soundex('word');
select patindex('%a', 'ta'), patindex('%ac%', 'jack'), patindex('dex%', 'dexjack');--婚配字符索引
select 'a' + space(2) + 'b', 'c' + space(5) + 'd';--輸入空格
select charIndex('o', 'hello world');--查找索引
select charIndex('o', 'hello world', 6);--查找索引
select quoteName('abc[]def'), quoteName('123]45');
--准確數字
select str(123.456, 2), str(123.456, 3), str(123.456, 4);
select str(123.456, 9, 2), str(123.456, 9, 3), str(123.456, 6, 1), str(123.456, 9, 6);
select difference('hello', 'helloWorld');--比擬字符串雷同
select difference('hello', 'world');
select difference('hello', 'llo');
select difference('hello', 'hel');
select difference('hello', 'hello');
select replace('abcedef', 'e', 'E');--調換字符串
select stuff('hello world', 3, 4, 'ABC');--指定地位調換字符串
select replicate('abc#', 3);--反復字符串
select subString('abc', 1, 1), subString('abc', 1, 2), subString('hello Wrold', 7, 5);--截取字符串
select len('abc');--前往長度
select reverse('sqlServer');--反轉字符串
select left('leftString', 4);--取右邊字符串
select left('leftString', 7);
select right('leftString', 6);--取左邊字符串
select right('leftString', 3);
select lower('aBc'), lower('ABC');--小寫
select upper('aBc'), upper('abc');--年夜寫
--去失落右邊空格
select ltrim(' abc'), ltrim('# abc#'), ltrim(' abc');
--去失落左邊空格
select rtrim(' abc '), rtrim('# abc# '), rtrim('abc');
6、 平安函數
select current_user;
select user;
select user_id(), user_id('dbo'), user_id('public'), user_id('guest');
select user_name(), user_name(1), user_name(0), user_name(2);
select session_user;
select suser_id('sa');
select suser_sid(), suser_sid('sa'), suser_sid('sysadmin'), suser_sid('serveradmin');
select is_member('dbo'), is_member('public');
select suser_name(), suser_name(1), suser_name(2), suser_name(3);
select suser_sname(), suser_sname(0x01), suser_sname(0x02), suser_sname(0x03);
select is_srvRoleMember('sysadmin'), is_srvRoleMember('serveradmin');
select permissions(object_id('student'));
select system_user;
select schema_id(), schema_id('dbo'), schema_id('guest');
select schema_name(), schema_name(1), schema_name(2), schema_name(3);
7、 體系函數
select app_name();--以後會話的運用法式稱號
select cast(2011 as datetime), cast('10' as money), cast('0' as varbinary);--類型轉換
select convert(datetime, '2011');--類型轉換
select coalesce(null, 'a'), coalesce('123', 'a');--前往其參數中第一個非空表達式
select collationProperty('Traditional_Spanish_CS_AS_KS_WS', 'CodePage');
select current_timestamp;--以後時光戳
select current_user;
select isDate(getDate()), isDate('abc'), isNumeric(1), isNumeric('a');
select dataLength('abc');
select host_id();
select host_name();
select db_name();
select ident_current('student'), ident_current('classes');--前往主鍵id的最年夜值
select ident_incr('student'), ident_incr('classes');--id的增量值
select ident_seed('student'), ident_seed('classes');
select @@identity;--最初一次自增的值
select identity(int, 1, 1) as id into tab from student;--將studeng表的烈屬,以/1自增情勢創立一個tab
select * from tab;
select @@rowcount;--影響行數
select @@cursor_rows;--前往銜接上翻開的游標確當前限制行的數量
select @@error;--T-SQL的毛病號
select @@procid;
8、 設置裝備擺設函數
set datefirst 7;--設置每周的第一天,表現周日
select @@datefirst as '禮拜的第一天', datepart(dw, getDate()) AS '明天是禮拜';
select @@dbts;--前往以後數據庫獨一時光戳
set language 'Italian';
select @@langId as 'Language ID';--前往說話id
select @@language as 'Language Name';--前往以後說話稱號
select @@lock_timeout;--前往以後會話確當前鎖定超時設置(毫秒)
select @@max_connections;--前往SQL Server 實例許可同時停止的最年夜用戶銜接數
select @@MAX_PRECISION AS 'Max Precision';--前往decimal 和numeric 數據類型所用的精度級別
select @@SERVERNAME;--SQL Server 的當地辦事器的稱號
select @@SERVICENAME;--辦事名
select @@SPID;--以後會話過程id
select @@textSize;
select @@version;--以後數據庫版本信息
9、 體系統計函數
select @@CONNECTIONS;--銜接數
select @@PACK_RECEIVED;
select @@CPU_BUSY;
select @@PACK_SENT;
select @@TIMETICKS;
select @@IDLE;
select @@TOTAL_ERRORS;
select @@IO_BUSY;
select @@TOTAL_READ;--讀取磁盤次數
select @@PACKET_ERRORS;--產生的收集數據包毛病數
select @@TOTAL_WRITE;--sqlserver履行的磁盤寫入次數
select patIndex('%soft%', 'microsoft SqlServer');
select patIndex('soft%', 'software SqlServer');
select patIndex('%soft', 'SqlServer microsoft');
select patIndex('%so_gr%', 'Jsonisprogram');
10、 用戶自界說函數
# 檢查以後數據庫一切函數
--查詢一切已創立函數
select definition,* from sys.sql_modules m join sys.objects o on m.object_id = o.object_id
and type in('fn', 'if', 'tf');
# 創立函數
if (object_id('fun_add', 'fn') is not null)
drop function fun_add
go
create function fun_add(@num1 int, @num2 int)
returns int
with execute as caller
as
begin
declare @result int;
if (@num1 is null)
set @num1 = 0;
if (@num2 is null)
set @num2 = 0;
set @result = @num1 + @num2;
return @result;
end
go
挪用函數
select dbo.fun_add(id, age) from student;
--自界說函數,字符串聯接
if (object_id('fun_append', 'fn') is not null)
drop function fun_append
go
create function fun_append(@args nvarchar(1024), @args2 nvarchar(1024))
returns nvarchar(2048)
as
begin
return @args + @args2;
end
go
select dbo.fun_append(name, 'abc') from student;
# 修正函數
alter function fun_append(@args nvarchar(1024), @args2 nvarchar(1024))
returns nvarchar(1024)
as
begin
declare @result varchar(1024);
--coalesce前往第一個不為null的值
set @args = coalesce(@args, '');
set @args2 = coalesce(@args2, '');;
set @result = @args + @args2;
return @result;
end
go
select dbo.fun_append(name, '#abc') from student;
# 前往table類型函數
--前往table對象函數
select name, object_id, type from sys.objects where type in ('fn', 'if', 'tf') or type like '%f%';
if (exists (select * from sys.objects where type in ('fn', 'if', 'tf') and name = 'fun_find_stuRecord'))
drop function fun_find_stuRecord
go
create function fun_find_stuRecord(@id int)
returns table
as
return (select * from student where id = @id);
go
select * from dbo.fun_find_stuRecord(2);