SQL 實現Excel 的10個常用功能
SQL 實現Excel 的10個常用功能
資料來源: https://mp.weixin.qq.com/s/4jS0l6YDsGuu8uWNukNz6A
01.關聯公式:Vlookup
--vlookup是excel幾乎最常用的公式,一般用於兩個表的關聯查詢等。所以我先創建一個新表:複製sale表並篩選出地區僅為廣州的,命名為sale_guang。 create table sale_guang SELECT * from sale where city="广州"; --需求:根據訂單明細號關聯兩表,並且sale_guang只有訂單明細號與利潤兩列 SELECT * from sale a inner JOIN (SELECT ordernum,profit from sale_guang) b on a.ordernum=b.ordernum
02.對比兩列差異
--需求:對比sale的訂單明細號與sale_guang訂單明細號的差異; SELECT * from sale a WHERE a.ordernum not in (SELECT b.ordernum from sale_guang b);
03.去除重複值
--需求:去除業務員編碼的重複值 SELECT * FROM sale where salesnum not in (SELECT salesnum from sale GROUP BY salesman HAVING COUNT(salesnum)>1)
04.缺失值處理
--需求:用0填充缺失值或則刪除有地區名稱缺失值的行。 --用0填充: update sale set city = 0 where city = NULL --删除有缺失值的行: delete from sale where city = NULL;
05.多條件篩選
--需求:想知道業務員張愛,在北京區域賣的商品訂單金額大於等於6000的信息。 SELECT * from sale where salesman = "张爱" and city = "北京" and orderaccount >=6000;
06. 模糊篩選數據
--需求:篩選存貨名稱含有"三星"或則含有"索尼"的信息。 SELECT * from sale where inventoryname like "%三星%" or 存货名称 like "%索尼%";
07.分類+統計(總和)
--需求:北京區域各業務員的利潤總額。 SELECT city,sum(`profit`) from sale WHERE city = "北京" GROUP BY `city`;
08.條件計算
--有多少个? SELECT COUNT(*) from sale where inventoryname like "%三星%" and `tax` > 1000 ; --这些订单的利润总和和平均利润是多少? SELECT `ordernum`,SUM(profit),AVG(`profit`) from sale where inventoryname like "%三星%" and `tax` > 1000 GROUP BY `ordernum`;
09.刪除數據間的空格(字串頭尾空白)
SELECT trim(inventoryname) from sale;
10.合併(欄位四則運算)與排序列
SELECT city,ordernum, (Nontaxamount - profit) as cost from sale order by cost DESC;