夢幻之旅

          DEBUG - 天道酬勤

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            671 隨筆 :: 6 文章 :: 256 評論 :: 0 Trackbacks
          1.先創建表
          create table employee (empid int ,deptid int ,salary decimal(10,2));

          2.插入記錄
          insert into employee values(1,10,5500.00);
          insert into employee values(2,10,4500.00);
          insert into employee values(3,20,1900.00);
          insert into employee values(4,20,4800.00);
          insert into employee values(5,40,6500.00);
          insert into employee values(6,40,14500.00);
          insert into employee values(7,40,44500.00);
          insert into employee values(8,50,6500.00);
          insert into employee values(9,50,750 0.00);


          3.語句講解
          row_number() over([partition by col1] order by col2)) as 別名

          此語句表示,根據cole1分組,  在分組內部根據col2進行排序。
          而這個別名表示,每個組內排序的順序編號(組內連接唯一).

          4.具體看個例子
          SELECT 
                 empid,
                 deptid,
                 salary,
                 row_number() 
          OVER(PARTITION BY deptid ORDER BY salary DESC) salary_order 
          FROM employee;
          結果如下

          延伸一下, 如果是按某個字段分組然后從每組取出最大的一條紀錄,只需加一個條件,salary_order=1
          sql代碼如下:
          SELECT 
              t1.empid,
              t1.deptid,
              t1.salary
          FROM (
              
          SELECT 
                 empid,
                 deptid,
                 salary,
                 row_number() 
          OVER(PARTITION BY deptid ORDER BY salary DESC) salary_order 
              
          FROM employee
              ) t1
          WHERE t1.salary_order=1;

          再延伸一下,根據部門分組,再按部門內的個人薪水排序,逐個累加。
          SELECT 
              empid,
              deptid,
              salary,
              
          sum(salary) OVER(PARTITION BY deptid ORDER BY salary DESC) ts   
          FROM employee

          5.partition by 與 group by 的區別
             1).partition by能得到統計后的明細數據, group by 只能得到匯總數據。
             2).partition by在from前, group 在 where 后.
          posted on 2011-08-25 14:08 HUIKK 閱讀(1024) 評論(0)  編輯  收藏 所屬分類: DataBase
          主站蜘蛛池模板: 庆元县| 耿马| 铜鼓县| 綦江县| 福贡县| 凉山| 凌源市| 龙里县| 特克斯县| 合肥市| 牙克石市| 方城县| 平远县| 桑植县| 筠连县| 亚东县| 杂多县| 三亚市| 长沙县| 兰溪市| 永济市| 新平| 洛扎县| 长汀县| 中超| 华蓥市| 侯马市| 宕昌县| 宜春市| 洛川县| 突泉县| 铜梁县| 元朗区| 恩施市| 申扎县| 浪卡子县| 望谟县| 宝应县| 泰安市| 靖江市| 松溪县|