資料分組
阿新 • • 發佈:2018-11-09
前面我們講解了聚合函式的使用,比如要檢視年齡為23歲員工的人數,只要執行下面的SQL就可以:
SELECT COUNT(*) FROM T_Employee WHERE FAge=23
可是如果我們想檢視每個年齡段的員工的人數怎麼辦呢?一個辦法是先得到所有員工的年齡段資訊,然後分別查詢每個年齡段的人數,顯然這樣是非常低效且煩瑣的。這時候就是陣列分組開始顯現威力的時候了。
為了更好的演示本節中的例子,我們為T_Employee表增加兩列,分別為表示其所屬分公司的FSubCompany欄位和表示其所屬部門的FDepartment,在不同的資料庫下執行相應的SQL語句:
MYSQL,MSSQLServer,DB2:
ALTER TABLE T_Employee ADD FSubCompany VARCHAR(20); ALTER TABLE T_Employee ADD FDepartment VARCHAR(20);
Oracle:
ALTER TABLE T_Employee ADD FSubCompany VARCHAR2(20); ALTER TABLE T_Employee ADD FDepartment VARCHAR2(20);
兩個欄位新增完畢後還需要將表中原有資料行的這兩個欄位值更新,執行下面的SQL語句:
UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Development" WHERE FNumber="DEV001"; UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="Development" WHERE FNumber="DEV002"; UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="HumanResource" WHERE FNumber="HR001"; UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="HumanResource" WHERE FNumber="HR002"; UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="InfoTech" WHERE FNumber="IT001"; UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="InfoTech" WHERE FNumber="IT002"; UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Sales" WHERE FNumber="SALES001"; UPDATE T_Employee SET FSubCompany="Beijing",FDepartment="Sales" WHERE FNumber="SALES002"; UPDATE T_Employee SET FSubCompany="ShenZhen",FDepartment="Sales" WHERE FNumber="SALES003";