select中的组编号(Oracle)

时间:2010-12-20 15:27:25

标签: sql oracle

我有一个以下示例 - 包含姓名,部门和国家/地区的表格。我需要创建一个select语句,列出所有记录,并为每个部门和国家/地区分配唯一编号(示例中的列组):

Name   Department   Country   Group
====== ============ ========= =====
James  HR           UK        1
John   HR           UK        1
Alice  Finance      UK        2
Bob    Finance      DE        3
Frank  Finance      DE        3

我想到了一些具有分析功能的select,但我发现只有row_number() over (partition by department, country)对组内的记录进行编号而不是组自身。你知道如何解决这个问题吗?谢谢!

2 个答案:

答案 0 :(得分:10)

SELECT  t.*, q.grp
FROM    (
        SELECT  q.*, rownum AS grp
        FROM    (
                SELECT  DISTINCT department, country
                FROM    mytable
                ORDER BY
                        department, country
                ) q
        ) q
JOIN    mytable t
ON      t.department = q.department
        AND t.country = q.country 

SELECT  t.*, DENSE_RANK() OVER (ORDER BY department desc, country desc) AS grp
FROM    mytable

答案 1 :(得分:0)

它有点笨拙,但你可以在表上做一个子查询(或者在这种情况下使用with子句)来获得每个国家的不同部门,然后从中得到rownum。

set echo on

DROP TABLE TESTXX

 DROP TABLE TESTXX succeeded.
CREATE
    TABLE TESTXX
    (
      NAME       VARCHAR2 ( 10 )
    , DEPARTMENT VARCHAR2 ( 15 )
    , COUNTRY    VARCHAR2 ( 2 )
    ) 

CREATE  succeeded.
INSERT INTO TESTXX VALUES
    ( 'James', 'HR', 'UK'
    ) 

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'John', 'HR', 'UK'
    ) 

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Alice', 'FI', 'UK'
    ) 

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Bob', 'FI', 'DE'
    ) 

1 rows inserted
INSERT INTO TESTXX VALUES
    ( 'Frank', 'FI', 'DE'
    ) 

1 rows inserted

WITH
    X AS
    (SELECT
        XX.*
      , ROWNUM R
      FROM
        (SELECT
            DEPARTMENT
          , COUNTRY
          FROM
            TESTXX
          GROUP BY
            COUNTRY
          , DEPARTMENT
          ORDER BY
            COUNTRY DESC
          , DEPARTMENT DESC
        ) XX
    )
  SELECT
      T.*
    , X.R
    FROM
      TESTXX T
    INNER JOIN X
    ON
      T.DEPARTMENT  = X.DEPARTMENT
      AND T.COUNTRY = X.COUNTRY
    ORDER BY
      T.COUNTRY DESC
    , T.DEPARTMENT DESC

NAME       DEPARTMENT      COUNTRY R                      
---------- --------------- ------- ---------------------- 
James      HR              UK      1                      
John       HR              UK      1                      
Alice      FI              UK      2                      
Bob        FI              DE      3                      
Frank      FI              DE      3                      

5 rows selected