Group by groups

I have a lot of data that I need to transform and "group of groups". Let me explain with an example:
SQL> create table orig_data as
  2  select distinct job, deptno
  3  from scott.emp e
  4  /

Table created.

SQL> select job
  2       , deptno
  3    from orig_data
  4   order by
  5         job
  6       , deptno
  7  /

JOB           DEPTNO
--------- ----------
ANALYST           20
CLERK             10
CLERK             20
CLERK             30
MANAGER           10
MANAGER           20
MANAGER           30
PRESIDENT         10
SALESMAN          30

9 rows selected.
Real-world data about 5 million lines.

I have a working group (I use xmlagg here because I'm on version 11.1 and therefore no listagg ;-))):
SQL> select od.job
  2       , rtrim(xmlagg(xmlelement(d,od.deptno,',').extract('//text()') order by od.deptno),',') deptnos
  3    from orig_data od
  4   group by od.job
  5  /

JOB       DEPTNOS
--------- ------------------------------
ANALYST   20
CLERK     10,20,30
MANAGER   10,20,30
PRESIDENT 10
SALESMAN  30
I note here that the two jobs CLERK and MANAGER has the same set of deptnos.
So if I group by deptnos I get this result:
SQL> select s2.deptnos
  2       , rtrim(xmlagg(xmlelement(j,s2.job,',').extract('//text()') order by s2.job),',') jobs
  3    from (
  4     select od.job
  5          , rtrim(xmlagg(xmlelement(d,od.deptno,',').extract('//text()') order by od.deptno),',') deptnos
  6       from orig_data od
  7      group by od.job
  8         ) s2
  9   group by s2.deptnos
 10  /

DEPTNOS                        JOBS
------------------------------ ------------------------------
10                             PRESIDENT
10,20,30                       CLERK,MANAGER
20                             ANALYST
30                             SALESMAN
My requirement is to identify all of these unique groups of deptnos in my table of orig_data, give each group as a surrogate key in a parent table and then populate two tables of children with the deptnos of each group and the jobs that have this group of deptnos:
SQL> create table groups (
  2     groupkey number primary key
  3  )
  4  /

Table created.

SQL> create table groups_depts (
  2     groupkey number references groups (groupkey)
  3   , deptno number(2)
  4  )
  5  /

Table created.

SQL> create table groups_jobs (
  2     groupkey number references groups (groupkey)
  3   , job varchar2(9)
  4  )
  5  /

Table created.
For the substitution groupkey I can use a rownumber on my group by query deptnos:
SQL> select row_number() over (order by s2.deptnos) groupkey
  2       , s2.deptnos
  3       , rtrim(xmlagg(xmlelement(j,s2.job,',').extract('//text()') order by s2.job),',') jobs
  4    from (
  5     select od.job
  6          , rtrim(xmlagg(xmlelement(d,od.deptno,',').extract('//text()') order by od.deptno),',') deptnos
  7       from orig_data od
  8      group by od.job
  9         ) s2
 10   group by s2.deptnos
 11  /

  GROUPKEY DEPTNOS                        JOBS
---------- ------------------------------ ------------------------------
         1 10                             PRESIDENT
         2 10,20,30                       CLERK,MANAGER
         3 20                             ANALYST
         4 30                             SALESMAN
This application, that I can use for a (slow) insert in my three tables in this simple way:
SQL> begin
  2     for g in (
  3        select row_number() over (order by s2.deptnos) groupkey
  4             , s2.deptnos
  5             , rtrim(xmlagg(xmlelement(j,s2.job,',').extract('//text()') order by s2.job),',') jobs
  6          from (
  7           select od.job
  8                , rtrim(xmlagg(xmlelement(d,od.deptno,',').extract('//text()') order by od.deptno),',') deptnos
  9             from orig_data od
 10            group by od.job
 11               ) s2
 12         group by s2.deptnos
 13     ) loop
 14        insert into groups values (g.groupkey);
 15
 16        insert into groups_depts
 17           select g.groupkey
 18                , to_number(regexp_substr(str, '[^,]+', 1, level)) deptno
 19             from (
 20                    select rownum id
 21                         , g.deptnos str
 22                      from dual
 23                  )
 24           connect by instr(str, ',', 1, level-1) > 0
 25                  and id = prior id
 26                  and prior dbms_random.value is not null;
 27
 28        insert into groups_jobs
 29           select g.groupkey
 30                , regexp_substr(str, '[^,]+', 1, level) job
 31             from (
 32                    select rownum id
 33                         , g.jobs str
 34                      from dual
 35                  )
 36           connect by instr(str, ',', 1, level-1) > 0
 37                  and id = prior id
 38                  and prior dbms_random.value is not null;
 39
 40     end loop;
 41  end;
 42  /

PL/SQL procedure successfully completed.
The tables now with these data:
SQL> select *
  2    from groups
  3   order by groupkey
  4  /

  GROUPKEY
----------
         1
         2
         3
         4

SQL> select *
  2    from groups_depts
  3   order by groupkey, deptno
  4  /

  GROUPKEY     DEPTNO
---------- ----------
         1         10
         2         10
         2         20
         2         30
         3         20
         4         30

6 rows selected.

SQL> select *
  2    from groups_jobs
  3   order by groupkey, job
  4  /

  GROUPKEY JOB
---------- ---------
         1 PRESIDENT
         2 CLERK
         2 MANAGER
         3 ANALYST
         4 SALESMAN
I can now these data the same result as before (just to test, I created the desired data):
SQL> select g.groupkey
  2       , d.deptnos
  3       , j.jobs
  4    from groups g
  5    join (
  6           select groupkey
  7                , rtrim(xmlagg(xmlelement(d,deptno,',').extract('//text()') order by deptno),',') deptnos
  8             from groups_depts
  9            group by groupkey
 10         ) d
 11         on d.groupkey = g.groupkey
 12    join (
 13           select groupkey
 14                , rtrim(xmlagg(xmlelement(j,job,',').extract('//text()') order by job),',') jobs
 15             from groups_jobs
 16            group by groupkey
 17         ) j
 18         on j.groupkey = g.groupkey
 19  /

  GROUPKEY DEPTNOS                        JOBS
---------- ------------------------------ ------------------------------
         1 10                             PRESIDENT
         2 10,20,30                       CLERK,MANAGER
         3 20                             ANALYST
         4 30                             SALESMAN
So far so good. It works all the pretty much as desired - with the exception of a couple things:

The insertion code very simple loop will be slow. OK, it's a work of unique conversion (in theory, but very few times at least), so that could probably be acceptable (except for my professional pride ;-).)

But it's worse, I have groups where the aggregation of string does not work - the chain should be about varchar2 (10000) which does not work in SQL in the group by :-(.

So I tried an attempt from the collections. First a collection of deptnos:
SQL> create type deptno_tab_type as table of number(2)
  2  /

Type created.

SQL> select od.job
  2       , cast(collect(od.deptno order by od.deptno) as deptno_tab_type) deptnos
  3    from orig_data od
  4   group by od.job
  5  /

JOB       DEPTNOS
--------- ------------------------------
ANALYST   DEPTNO_TAB_TYPE(20)
CLERK     DEPTNO_TAB_TYPE(10, 20, 30)
MANAGER   DEPTNO_TAB_TYPE(10, 20, 30)
PRESIDENT DEPTNO_TAB_TYPE(10)
SALESMAN  DEPTNO_TAB_TYPE(30)
All very good - no problem here. But then a collection of jobs:
SQL> create type job_tab_type as table of varchar2(9)
  2  /

Type created.

SQL> select s2.deptnos
  2       , cast(collect(s2.job order by s2.job) as job_tab_type) jobs
  3    from (
  4     select od.job
  5          , cast(collect(od.deptno order by od.deptno) as deptno_tab_type) deptnos
  6       from orig_data od
  7      group by od.job
  8         ) s2
  9   group by s2.deptnos
 10  /
 group by s2.deptnos
          *
ERROR at line 9:
ORA-00932: inkonsistente datatyper: forventede -, fik XAL_SUPERVISOR.DEPTNO_TAB_TYPE
Now, it fails - I can't group by a collection data type...

I'm not asking anyone to write my code, but I know that there are sharper brains out there on the forums of ;-).

Someone would have an idea of something I could try that will allow me to create these "groups of groups" even for large aggregation of chain that technical groups can manage?

Thanks for any help, advice or tips ;-)

The issue of "group-by-collection" can be resolved by creating a container object on which we define a method of CONTROL:

SQL> create type deptno_container as object (
  2    nt deptno_tab_type
  3  , order member function match (o deptno_container) return integer
  4  );
  5  /

Type created

SQL> create or replace type body deptno_container as
  2    order member function match (o deptno_container) return integer is
  3    begin
  4      return case when nt = o.nt then 0 else 1 end;
  5    end;
  6  end;
  7  /

Type body created
 

Then an INSERT statement can do the job, after unnesting collections:

SQL> insert all
  2    when rn0 = 1 then into groups (groupkey) values (gid)
  3    when rn1 = 1 then into groups_jobs (groupkey, job) values(gid, job)
  4    when rn2 = 1 then into groups_depts (groupkey, deptno) values(gid, deptno)
  5  with all_groups as (
  6    select s2.deptnos
  7         , cast(collect(s2.job order by s2.job) as job_tab_type) jobs
  8         , row_number() over(order by null) gid
  9    from (
 10      select od.job
 11           , deptno_container(
 12               cast(collect(od.deptno order by od.deptno) as deptno_tab_type)
 13             ) deptnos
 14      from orig_data od
 15      group by od.job
 16    ) s2
 17    group by s2.deptnos
 18  )
 19  select gid
 20       , value(j) job
 21       , value(d) deptno
 22       , row_number() over(partition by gid order by null) rn0
 23       , row_number() over(partition by gid, value(j) order by null) rn1
 24       , row_number() over(partition by gid, value(d) order by null) rn2
 25  from all_groups t
 26     , table(t.jobs) j
 27     , table(t.deptnos.nt) d
 28  ;

15 rows inserted

SQL> select * from groups;

  GROUPKEY
----------
         1
         2
         3
         4

SQL> select * from groups_jobs;

  GROUPKEY JOB
---------- ---------
         1 SALESMAN
         2 PRESIDENT
         3 CLERK
         3 MANAGER
         4 ANALYST

SQL> select * from groups_depts;

  GROUPKEY DEPTNO
---------- ------
         1     30
         2     10
         3     10
         3     30
         3     20
         4     20

6 rows selected
 

Works very well on the sample data, but how this approach is changing on much (much) more large data set is another story :)

Tags: Database

Similar Questions

  • When I send a mass text by enabling / disabling message group, then I turn on message group, suddenly became a group text responses?

    When I send a mass text by enabling / disabling message group, then I turn on message group, suddenly became a group text responses?

    I sometimes send jokes or notifications to multiple contacts.  After I mass text them by activating / deactivating iMessage and Group Messages, then I switch on iMessage and Group Messages - will people I sent a mass text message can see phone numbers and the responses of the other?

    I think it should not because after sending the text it comes just up on their phone as a text message you only, but I want to just make sure

    Thank you

    Hello Eddie7777,

    Thanks for your post. I understand that you wanted to confirm if a mass message will convert to a group message after activating again Group Messaging. I certainly understand wanting to send a mass text message without launching a group of crazy message where number of all is shared. I'll be more than happy to help clarify.

    I tested on my iPhone, and so my previous knowledge on the messages, I discovered some great information. When you send a mass text with disabled group messaging message, it sends the messages individually and these other people only get a text without your mass SMS numbers. When you have enabled messaging group once again, it won't change the message on their end, and if they say it will for you.

    Hope this helps explain things!

    Take care!

  • Show all members of the Group of developer tools?

    How can I view all of the current members of the developer tools group?

    Hello Michael,

    Unfortunately, it is quite difficult. Here are some solutions:

    http://superuser.com/questions/279891/list-all-members-of-a-group-Mac-OS-x

    https://jamfnation.jamfsoftware.com/discussion.html?ID=15503

  • How can I create a group through Outlook without the application Outlook email?

    How can I create a group by using Outlook without an application Outlook email?

    Sigmalambda wrote:

    How can I create a group by using Outlook without an application Outlook email?

    It is difficult to understand what you're trying to do. You can create a group and send an email to the group in any mail client. The recipients can use any e-mail provider or an e-mail client to receive e-mail. Please explain in more detail what you are trying to accomplish.

  • iMessages group Conversation does not go in DND

    I've just updated to iOS 10 on my iPhone more than 6 and a group conversation in the Messages that I sometimes put on DND now does not recognize that the conversation has been implemented within DND.  Messages continues to inform me about all messages from anyone in the group.  Is there any solution for this?

    Thank you

    Brent

    Have what troubleshooting you tried? Troubleshooting user steps include reboot, reset, restore from backup, restore to factory; tests after each stage.

    If you return in the message after the ignition of the DND, does always show as it is turned on?

  • I restored my iPhone 6 from an itunes backup, but my group chat contacts are changed

    So I backed up my iphone on itunes because I went to the apple store to solve a problem I had. After that that they had deleted everything on my phone, I went home and tried to restore it. All went well, all my contacts were saved, my pictures, etc. so I waited so he could complete the synchronization for my laptop. While I was checking my messages, I noticed that many of the cats from group I had, had shared some of my names of friends with other people on my contact list. I also saw that other people who were in the GM had their photo ID, but instead of their name, their phone numbers were posted. I rebooted my phone and hope so that it can be corrected, but it didn't, I also tried to add the people who did not appear in the newsgroup, but I have added to them, the person that they have been replaced by a show! If anyone can help me on how to solve this problem, it would be highly appreciated!

    Hello, arsmars!

    Thank you for using communities of Apple Support. Looks like your Contacts are not being very cooperative since you have restored your iPhone iOS 10 6. I know that I have not memorized a phone number in ages and would need this support as soon as possible. I'll be happy to help you.

    It seems that you use iCloud to synchronize contacts between devices. On your iPhone, go to settings > iCloud. Disable the Contacts, wait 5 seconds, then turn it back on and check your Messages and Contacts.  I have a link below if you are still having problems:

    Get help using iCloud Contacts, calendars, or reminders

    I wish you a great weekend!

  • IOS 10 Notifications: Please bring back ability to group by app notifications

    Please, please, please bring back the ability to group by app notifications...

    And why Apple consider it an improvement "," to take away our ability to choose how we sort our notifications in the first place? Not happy at all to this subject :-(. Some of us are _a_lot_ notifications, and also be able to group by app notifications means that we can then _clear_ notifications by app, as well (i.e. clear specific _types_ of the notifications at a time), which is VERY useful... With respect, this is a gross oversight on the part of Apple. I'm an ardent loyal fan, very long Apple products, but 'small', absurd decisions like this add up, making it more difficult and more difficult to justify is not something else.

    -Thank you!

    Apple is not read here.

    Submit your Apple asking this feature here:

    http://www.Apple.com/feedback

  • iOS 10 - auto bluetooth with contact group synchronization

    I have my iPhone 5s coupled to my car bluetooth hands-free system.

    With iOS 9 I was able to sync only certain groups of Contacts from iPhone. It was helpful that I have a number of groups in iPhone Contacts, including one specially created for syncing to my car.

    Since the update of my iPhone to iOS 10, I have that option in the bluetooth settings of the iPhone to check any combination of 'Favorite phone', "Phone Recents" or "All Contacts". None of them are useful for me as I want to synchronize with one of the original groups in Contacts.

    Help, please!

    Thank you.

    The same problem. A month ago I could synchronize specific groups with the phone book from my car. Now, the only option is "Contact".  Help!

  • add/delete a contact group message iOS 10

    Can't seem to find how to delete/add contact group message since the update to iOS on iPhone 10 6. Solutions?

    nessrez wrote:

    Can't seem to find how to delete/add contact group message since the update to iOS on iPhone 10 6. Solutions?

    Send a message from your iPhone, iPad or iPod touch - Apple Support Group

    This is possible with an imessage group all users using an Apple device.

    You can't do it for a group message MMS - mix Apple and not Apple device device.

  • iOS 10 - how to group by app notifications?

    I just downloaded and installed the new 10 iOS and the first thing I noticed that I want to change is the notifications. I would like to bring grouped by app once again, how I put them up on iOS 9. However, I can't find this option anywhere in the settings. Can someone please tell me how I can change this setting, or if it is no longer an option?

    Thank you in advance.

    You are right. The new Notification Center so difficult of our lives and our long

    Please Apple return the old function "sort by apps.

  • If I go buy Apple Watch nike, that I can use other groups like leather band?

    If I go buy Apple Watch nike, that I can use other groups like leather band?

    At this point, all we know is here:

    https://www.Apple.com/Apple-watch-Nike/

  • I do my job to the computer on a MAC computer. I want to create a document using Pages and then convert the document to PDF and send a group email. I want to send the PDF using the pdf for each receiver icon must click the icon to open t

    I do my job to the computer on a MAC book PRO. I want to create a document using Pages and then convert the document to PDF and send a group email. I want to send the PDF using the pdf for each receiver icon must click the icon to open the document. My problem is the document does not show the icon, but rather the document is already open. I spoke with 2 Apple. 'Experts' care and can help me. Can someone tell me what to do?

    It's a question of how the recipients e-mail programs deal with attachments. Many e-mail programs will open all the files they can handle, including files jpg and PDF, by default, and if the recipient has not changed that there is nothing you can do about it. The only solution is to the compress first, then it will be delivered as an attachment, allowing the recipient to decompress and open it.

  • I can't see Group Conversations?

    My phone number has recently added 2 cats of Imessages group. For one of them, I personally entered the phone number. However, on my Iphone I can't see group conversations. I can't see any discussion group click on everything. I have group messages and MMS on. Also, I tried to reset the network settings, restart my Iphone and turn on/off Imessages. I currently have 9 Ios. Everyone in the group the cats have been the reception and sending of the messages that I don't know. Is there a solution?

    This article can help:

    Send a message from your iPhone, iPad or iPod touch - Apple Support Group

    To quote a few excerpts: If you send a message to group of people who don't use an iMessage, the message is sent as an MMS or SMS message.  Messages MMS & SMS groups appear in green text bubbles and go through your carrier instead of Apple. In addition, when you send an SMS to group, all responses are sent as individual text messages and recipients cannot see the other answers in the group.

    So, if you are having problems with Group SMS and MMS messages, I think you will need to contact your support provider.

  • Try to add my Mac to a Windows Home Group

    I have a Macbook pro and try to add to my home group (Windows)

    I can see my desktop or laptop in the finder on the MBP but there ask the office password, I entered every password I don't know and I have no reason to, where can I find the password or should I ask this question on a community of Windows?

    Thank you

    OS X Mavericks: set up a Windows computer to share files with Mac users

    OS X Yosemite: set up a Windows computer to share files with Mac users

    OS X El Capitan: set up a Mac to share files with Windows users

  • Contacts - assign group on import

    When the Yahoo address book importing (exported as a CSV file) is it possible during import the corresponding field to assign the category (the label of Yahoo) as a group?

    The idea is to bring in a few thousand emails, who have 10 groups of different sizes.

    I know that I can a) affect the other field label or Notes and then later b) search maps for names of previous groups, c) select all and then d) create each group. I hope that I can eliminate these steps.

    You could probably do with some AppleScript, but otherwise I don't think.

    I think that the simplest solution would be to divide the file into groups and import each separately. When you import, they all appear in the last Smart import group. You can then create your new group and drag them all since the last import in the new group.

  • Cannot receive MMS specific contact group

    I can send and receive SMS through Group MMS.  However, I have a particular contact that can receive messages via a MMS group, but I do not get one of his messages in the group.  We can as well send/receive individual iMessages to eachother perfectly.  I use an iPhone 6s, and my touch is the use of an iPhone 5 c. I checked to make sure that this contact is not blocked.  I thought that maybe it was a problem of carrier, but I recently changed property & t, sprint and iPhone 4s to a 6 s iPhone and this problem followed me across from media/devices.  I have this problem with a particular contact, and there seems to be a problem with my apple account.  This problem is happening constantly for more than a year. Any ideas what could be going wrong?

    Allie.j.t wrote:

    I can send and receive SMS through Group MMS.  However, I have a particular contact that can receive messages via a MMS group, but I do not get one of his messages in the group.  We can as well send/receive individual iMessages to eachother perfectly.  I use an iPhone 6s, and my touch is the use of an iPhone 5 c. I checked to make sure that this contact is not blocked.  I thought that maybe it was a problem of carrier, but I recently changed property & t, sprint and iPhone 4s to a 6 s iPhone and this problem followed me across from media/devices.  I have this problem with a particular contact, and there seems to be a problem with my apple account.  This problem is happening constantly for more than a year. Any ideas what could be going wrong?

    Your Apple account has nothing to do with sending MMS message, which is a feature of the carrier.

    If you encounter a problem with an individual then maybe the problem is on their side, have what troubleshooting they done?

Maybe you are looking for