ROW_NUMBER和数据分组

时间:2016-02-04 01:34:01

标签: sql sql-server

我有一个如下所示的数据: table1

我想要的是一个按GroupCode,Group Description,SubGroup和subgroup class分组的行号,我想保留按如下所示的帐户代码排序: table2

在对行号进行分组的同时设置行号的正确方法是什么?

3 个答案:

答案 0 :(得分:0)

您正在寻找DENSE_RANK窗口函数:

SELECT
    rn = DENSE_RANK() OVER(ORDER BY GroupCode, GroupDescription, SubgroupClass),
    *
FROM tbl
ORDER BY rn, AccountCode

答案 1 :(得分:0)

您正在寻找dense_rank()

select dense_rank() over (order by GroupCode, GroupDescription, SubGroup)
. . .

但是,这并不能保证accountCode的排序。这将需要更多的工作。首先,确定每个分组的最小帐户代码,然后使用dense_rank()

select t.*, dense_rank() over (order by minac)
from (select t.*,
             min(accountCode) over (partition by GroupCode, GroupDescription, SubGroup) as minac
      from t
     ) t

答案 2 :(得分:0)

我猜你需要这个

;WITH cte 
     AS (SELECT groupcode, 
                groupdescription, 
                subgroup, 
                subgroupclass, 
                Min(accountcode) AS accountcode 
         FROM   your_table 
         GROUP  BY groupcode, 
                   groupdescription, 
                   subgroup, 
                   subgroupclass), 
     ordr 
     AS (SELECT Row_number()OVER(ORDER BY accountcode) AS RN, 
                * 
         FROM   cte) 
SELECT C.rn, 
       A.* 
FROM   your_table A 
       INNER JOIN cte C 
               ON A.groupcode = C.groupcode 
                  AND A.groupdescription = C.groupdescription 
                  AND A.subgroup = C.subgroup 
                  AND A.subgroupclass = C.subgroupclass