Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbering of groups in select (Oracle)

Tags:

sql

oracle

I have a following example - table with name, department and country. I need to create a select statement that lists all records and assigns unique number to each group of department and country (column Group in the example):

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

I thought of some select with analytic function but I found only row_number() over (partition by department, country) which numbers records inside the group and not groups themselves. Do you have any idea how to solve this problem? Thank you!

like image 864
sax Avatar asked Dec 20 '10 15:12

sax


1 Answers

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 

or

SELECT  t.*, DENSE_RANK() OVER (ORDER BY department desc, country desc) AS grp
FROM    mytable
like image 85
Quassnoi Avatar answered Sep 17 '22 16:09

Quassnoi