Search code examples
sqloraclegroupingaggregationgroup-summaries

Oracle - Group-level summaries


I am trying to create a report that has a summary for each group. For example:

ID           NAME              COUNT           TOTAL     TYPE
-------------------------------------------------------------
1            Test 1            10                         A
2            Test 2            8                          A
                                               18

7            Mr. Test          9                          B
12           XYZ               4                          B
                                               13

25           ABC               3                          C
26           DEF               5                          C
19           GHIJK             1                          C
                                               9

I have a query that can do everything except the TOTAL columns:

       select sd.id DATA_REF_NUM ID, count(sd.DATA_DEF_ID) COUNT, defs.data_name NAME, sd.type
       from some_data sd, data_defs defs
       where sd.data_def_id = defs.data_def_id
       group by some_data.type, some_data.id, defs.data_nam
       order by some_data.id asc, count(amv.MSG_ID) desc ;

I'm just not sure how to get a summary on a group. In this case, I'm trying to get a sum of COUNT for each group of ID.

UPDATE:

Groups are by type. Forgot that in the original post.

TOTAL is SUM(COUNT) for each group.


Solution

  • How about using ROLLUP like...

    select sd.id DATA_REF_NUM ID, count(sd.DATA_DEF_ID) COUNT, defs.data_name NAME, sd.type from some_data sd, data_defs defs where sd.data_def_id = defs.data_def_id group by ROLLUP(some_data.type, (some_data.id, defs.data_nam)) order by some_data.id asc, count(amv.MSG_ID) desc ;

    This works for a similar example in my database, but I only did it over two columns, not sure how it will function over more...
    Hope this is helpful,
    Craig...

    EDIT: In a ROLLUP, columns you want to sum over but not subtotal over like id and data_nam should be lumped together inside the ROLLUP in parantheses)