1. 程式人生 > >SQL基礎知識點總結

SQL基礎知識點總結

SQL基礎知識點總結

常用語句的執行順序:
from–on–join–where–group by–cube/rollup–having–select–distinct–order by–limit

一、基礎查詢

select distinct product,number*2 as "資料",*,'商品' as "型別"
from table 1
where dt='2018-11-09'
and  not number>10
or product is not null
--AND 的運算優先順序高於OR
/*註釋語法的表示之二*/

二、聚合

  • 聚合函式:count sum avg max min
    需要注意的是null在參與計算的時候,計算合計值時null處理為0,計算平均值時null處理為0,但是數量上增加了一個;max min 處理的時候不參與計算;
  • group by (聚合鍵/分組列)
    需要注意的是:group by自居中不能使用select中列的別名;
    where 子句中不能使用聚合函式;
  • 常見錯誤
    select子句中有多餘的列
    group by子句中使用了列的別名
    group by結果能排序嗎–不是,結果順序隨機
    where 子句中使用聚合函式
  • 聚合鍵所對應的條件贏還是書寫在where子句中(兩個原因:理解和執行速度)
    where子句=指定行所對應的條件
    having子句=指定組所對應的條件

三、排序

  • order by (排序鍵)
    排序鍵中包含null時會在開頭和結尾進行彙總
    order by中可以使用列的別名
    可以使用select 子句中未出現的列和聚合函式
    不能使用列的編號(語法無誤,但閱讀困難,未來可能刪除)

四、複雜查詢

  • 檢視
create view 檢視名稱(檢視列名1,檢視列名2)
AS
<select 語句>

定義檢視時不能使用order by子句
對檢視進行更新時需要滿足一些條件

  • 標量子查詢
    必須且只能返回1行1列的結果
  • 關聯子查詢(和標量子查詢的關係感覺有點兒矛盾?)
    舉例:選出各分類中價格超過均值以上的分類
select 商品種類,商品名稱,價格
from table1 as P1
where C>(select avg(價格)
		   from table2 as P2
		   where P1.商品種類=P2.商品種類
		   group by 商品種類)

五、函式、謂詞、CASE表示式

  • 函式
    算術函式:abs/mod/round
    字串函式:concat/length/lower/replace/substring/upper
    日期函式:current_date/current_time/current_timestamp/extract
    轉換函式:cast/coalesce
    聚合函式:max/min/avg/count/sum
  • 謂詞
    like/between/is null/in/exists
  • case when then else end

六、集合運算(union/join)

  • union
    作為運算物件的記錄的列數必須相同
    作為運算物件的記錄中列的型別必須一致
    可以使用select,但order by 只能在最後使用一次
    包含:
    union all:並集,包含所有重複行
    intersect:交集
    except:差集
  • join
    inner join:內連線 兩個表都存在的資訊選出來
    outer join:外連結,任何一個表中存在的所有資料都選出來
    cross join:笛卡爾積,是所有其它join查詢的基礎

七、SQL高階處理

  • 視窗函式語法 <視窗函式> over (partition by <列清單> order by <列清單>),partition by 在橫向上進行了分組,order by 在縱向上進行了排序
  • 必須用在select子句,但是不能用在where/group by子句中
    種類:rank(相同位次跳過,1/1/3)/dense_rank(相同位次不跳過1/1/2)/row_number(唯一位次1/2/3)
    補充說明:row number 可以解決取最大值然後再inner join去重的方法,特別簡單;
  • 計算移動平均
avg() over(order by 欄位 rows 2 preceding) as name
avg() over(order by 欄位 rows 2 following) as name
avg() over(order by 欄位 rows between 1 preceding and 1 following) as name
  • rollup 同時得出合計和小計 語法:group by rollup (欄位1 欄位2),但是如果欄位有空的情況就會出現兩個有歧義的行,需要注意,為了避免這種情況,請使用grouping
    補充說明:roll up 可以解決group by只有小組合計,沒有總合計的問題,省去了union的麻煩。
  • grouping
select 
      case when grouping(欄位1)=1 then '欄位1合計' else 欄位1 end as name1
      case when grouping(欄位2)=1 then '欄位2合計' else 欄位2 end as name2
      sum(欄位3) as 欄位3合計
from table1
group by rollup(欄位1,欄位2)
--相當於group by() 和 group by (欄位1)
  • cube
select 
      case when grouping(欄位1)=1 then '欄位1合計' else 欄位1 end as name1
      case when grouping(欄位2)=1 then '欄位2合計' else 欄位2 end as name2
      sum(欄位3) as 欄位3合計
from table1
group by cube(欄位1,欄位2)
--相當於group by() 和 group by (欄位1)和group by(欄位2)