1. 程式人生 > >SqlServer中的查詢簡單總結

SqlServer中的查詢簡單總結

結果集 sqlserve having 不重復 結果 col 包含 sele HA

一、sql語句的執行順序

  查詢時數據庫中使用最多的操作,一條sql語句的查詢順序是

    1、from Tb1 [ join on ] 得到查詢的數據源

    2、where        對數據過濾(單條數據上過濾)

    3、group by 對數據分組

    4、having       篩選分組(在組別上進行過濾)

    5、select distinct     獲取結果集

    6、order by      對結果集排序

二、常用的查詢知識

直接上代碼

--1、空值查詢
    
    --例子:  查詢age(或者不為)為null的用戶
select * from Tb_UserInfo where Age is null select * from Tb_UserInfo where Age is not null --2、條件查詢 --註:where用於單條記錄篩選 --例子: 查詢年齡為21~23的用戶 select * from Tb_UserInfo where Age>=21 and Age<=23 select * from Tb_UserInfo where Age in(21,22,23) select * from Tb_UserInfo where
Age between 21 and 23 --3、聚合函數和分組 --註:這兩個應一起使用,單獨使用時沒有太大意義,沒有顯式地用group by分組時,所有數據為一組 --常用的聚合函數 count avg min max sum ;having 對分組進行篩選 --例子: 查詢使用角色的人數,且篩選角色的人數大於3的組 select roleid as 角色編號, COUNT(*) as 人數 from Tb_UserInfo group by roleid
having COUNT(*)>3 --查詢每種角色的人數和每種角色用戶的平均年齡 select roleid as 角色編號, COUNT(*) as 人數 , AVG(age) as 平均年齡 from Tb_UserInfo group by roleid --4、模糊查詢 --註: -表示單個字符; %表示任意個字符; [abc]表示是a/b/c; ^a表示不是a的字符 --例子: 查詢用戶名包含a的用戶 select * from Tb_UserInfo where username like %a% select * from Tb_UserInfo where UserName like _a%--username的第二個字符為a的用戶 --5、distinct、top和 order by --註:top和order by是一起使用的,先有排序才能有‘前幾條’記錄 --例子: 查詢不重復的用戶中的前3條記錄,按用戶id排序 select distinct top 3 * from Tb_UserInfo order by uid

SqlServer中的查詢簡單總結