It would be really nice if Views Calc was also able to group a view by a column and calculate a sum/average/count of another column.


  • Currently, Views Calc is able to calculate and display the sum of comments by user:
    user    nid    comments
    KarenS  1      11
    KarenS  2      9
    sun     1      4
    sun     2      8
    Sum     -      32
  • With additional grouping by user and removing the field nid in this view, Views Calc could calculate the sum of all comments in all nodes per user:
    user    comments
    KarenS  20
    sun     12
    Sum     32

Is this possible with Views Calc?

Members fund testing for the Drupal project. Drupal Association Learn more


ray007’s picture


moshe weitzman’s picture

Version: 5.x-1.x-dev » 6.x-1.x-dev

Since D6 Views has grouping, this is more likely to be implemented there (if at all).

KarenS’s picture

Actually, Views won't do any totaling of the group values, so we still need something else. But hopefully the new grouping in Views 2 will make this easier to do.

GregoryHeller’s picture

I noticed this too. If you select a field in the "Grouping Field" drop down in the "views calc style" settings in views2, the view will be grouped by the field you selected, and the views calc "total" line will show up at the bottom of each "grouping" of nodes, HOWEVER the total will always be the total of all rows! So if you have 5 groupings of a total of 25 nodes, and you are summing a column where the value of all the fields is "1" (thus the total sum is 25) this total will be shown below EACH grouping where one would expect to see a "sub total"

cardentey’s picture

subscribing :-)

PRZ’s picture


gunzip’s picture

subscribe. there's another module that does this anyway:
but it's in early developement stage. maybe joining forces ?

wundo’s picture

Title: Add grouping support for views » Add grouping support for views calc
Version: 6.x-1.x-dev » 6.x-1.0
StryKaizer’s picture


visualnotion’s picture

I've been racking my brain to figure out how to get this functionality only to find out it may not be possible, right now. Any ideas of how to group and total like Sun requested without Views_Calc?

I've got a sports league site I'm trying to finish developing and I was hoping to do a write-up on how it was done (seems to come up every now and then without a decent solution to date).

Any help in getting this implemented would be appreciated.

KarenS’s picture

The views_groupby field works totally differently than views_calc so I don't think they can be combined. Plus it only does counts.

We already have the grand totals and subtotals, so the remaining request would be an option to hide the source data and display only the totals, which should be fairly easy to add.

KarenS’s picture

As to #4, we have both grand totals and sub totals for each page (a recent change to the code).

As to #10, there are no easy alternative ways to do that, that is the purpose of this module. I use Views Calc extensively for things like sports team totals (see for some examples).

KarenS’s picture

Hmm... well there are actually a number of different things noted in this issue. I just added an option to surpress the details and show the totals only and it now shows both subtotals and grand totals. The one thing left is the original issue, which I mis-read or misunderstood, to be able to group by a field and then to calculations on that total. That is not yet implemented.

I'm going to push out a new release with a number of bug fixes. This feature will take more thought so it won't go in and will remain a feature request.

Daniel A. Beilinson’s picture

Hi, KarenS!
I try to get sum of money cck fields. And when i try to add to my table field with few taxonomy terms i see few rows with one term in one row. If i use group multiple values option i see sum of all rows without grouping multiple values... Can you fix it?
P.S. In new version i choose only sum and module gives me Total COUNT, Total SUM, Total AVG, Total MIN, Total MAX. Can you fix it?

KarenS’s picture

Please don't dump unrelated issues together, this is about a feature request for grouping. There is another issue about problems with multiple values and the project page says this is a known issue. The last thing is a bug that got introduced in the last commit, but it didn't belong in this issue either.

introfini’s picture


jrust’s picture


klahaeck’s picture


digitalproductionart’s picture


Aren Cambre’s picture

Version: 6.x-1.0 » 6.x-1.x-dev

subscribe. This would be quite useful. If I turn on grouping, I get no calcs at all on certain fields.

seabrawk’s picture


seabrawk’s picture

This isn't the same as displaying all the info on one page at the same time and so probably doesnt work for most of you, but you could create a grouping "taxonomy" for each thing you'd normally group, and and then expose that filter in your view as a selectable list...

li8461’s picture


JamieR’s picture


Also, incase anyone is interested, I solved my need to total a grouped field with a theme override function for my view... it ended up looking like this:

<div class="field-item">$<?php 
  /* Total all the grouped numbers. */
  foreach ($field->field_values[$row->nid] as $value) {
    $total += $value['value'];
  print $total; 

In a template file named views-view-field--field-charge-amount-value.tpl.php.
Hope that helps someone!

JamieR’s picture

I had someone ask me to explain this in a little more detail, so here goes.

I'm using this technique to total a CCK field that allows "Unlimited" values. You can total it in a view created by the Views 2 module, or in the normal node view. I'll just show how to do the Views 2 one. But I highly recommend installing the Advanced Help module. After installed, you can look to the CCK help page for info on how to theme the node view (help/content/theme-field-templates).

The field that I wanted to total is called field_charge_amount.

  1. Go to you view edit page and click on the "Theme: Information" link in the lower left.
  2. You should now see a (LARGE) list of theme override templates below. Find the theme template name for your field... mine was called Charge Amount, so I found this list:

    Field Content: Charge Amount (field_charge_amount) (ID: field_charge_amount_value): views-view-field.tpl.php, views-view-field--field-charge-amount-value.tpl.php, views-view-field--ro-print-tag.tpl.php, views-view-field--ro-print-tag--field-charge-amount-value.tpl.php, views-view-field--default.tpl.php, views-view-field--default--field-charge-amount-value.tpl.php, views-view-field--ro-print-tag--default.tpl.php, views-view-field--ro-print-tag--default--field-charge-amount-value.tpl.php

    It shows the active template that is being used in bold.

  3. If we want to override it for all cases of the field in a view, we will want to add a template file called views-view-field--field-charge-amount-value.tpl.php to your theme (/sites/default/themes/your_theme/). You just pick the name of the template that fits the amount of specificity you want for the field. Anyway, at this point click on the Field name at the beginning of this block to get the template file contents. Mine looked like this:
    // $Id: views-view-field.tpl.php,v 1.1 2008/05/16 22:22:32 merlinofchaos Exp $
      * This template is used to print a single field in a view. It is not
      * actually used in default Views, as this is registered as a theme
      * function which has better performance. For single overrides, the
      * template is perfectly okay.
      * Variables available:
      * - $view: The view object
      * - $field: The field handler object that can process the input
      * - $row: The raw SQL result that can be used
      * - $output: The processed output that will normally be used.
      * When fetching output from the $row, this construct should be used:
      * $data = $row->{$field->field_alias}
      * The above will guarantee that you'll always get the correct data,
      * regardless of any changes in the aliasing that might happen if
      * the view is modified.

    print $output;

  4. Next step is to make the file with the default content pasted into it and put it in your theme folder. When that is done I'd update the theme registry and reload the theme info page on the view to see if the bolded theme has changed to yours. The views theme info screen has a button at the bottom you can click to update the theme registry.
  5. Now you are ready to edit your new theme template file. I found the variables that I needed in the $field object, and needed to cros reference the view id from the $row object. My favorite way to look inside variables is with this line: drupal_set_message("<pre>".print_r($row,1)."</pre>");. You should be able to see just the important variables like this: drupal_set_message("<pre>".print_r($field->field_values[$row->node_vid],1)."</pre>");
  6. So now that you can get to your values, you can do whatever you want with them. In my final version I decided to output each row and then the total at the end with a different class so that I could style in a little dividing line above it. Here is what mine looked like:
      /* Total all the grouped numbers. */
      if (!empty($field->field_values[$row->{$field->field_alias}])) {
        foreach ($field->field_values[$row->{$field->field_alias}] as $value) {
          $total += $value['value'];
          print (!empty($value['value'])) ? '<div class="field-item">$'.$value['value']."</div>\n" : null;
        if ($total > $value['value']) {
          print '<div class="field-item-total">$'.$total."</div>\n";
      } else {
        print '<div class="field-item">none</div>'."\n"; 
  7. Then your last step is just to fancy it up with some css as normal and you're done!
  8. Hope that helps someone. Theme overriding can do some amazing, super useful stuff. Totaling a field is just one. :)
    Let me know if you have any questions. Thanks! Jamie.

seabrawk’s picture

First of all, thanks...

Secondly, I made it all the way to "updating the theme registry and reload the theme info page on the view to see if the bolded theme has changed to yours."

However, it never changed the bolded theme to mine, even after creating a txt file named (in my case) "views-view-field--field-stat-nonpass-td-value.tpl.php," which contained the default php text, and was placed in my "sites/default/modules/views/theme/" directory...

Lastly, From where does one run this command: "drupal_set_message("



Thanks again for all the help, and sorry if I am asking rudimentary stuff...

JamieR’s picture

No problem. The theme template file that you just made would go in /sites/default/themes/your_theme_name/ ... not in the views module's theme folder.
Then to answer your second question, the set message goes into that theme template file that you just put in there... Make sense?

Let me know - good luck!

doknet’s picture

Title: Add grouping support for views calc » RELATED QUESTION

I made a new post, with a matter related to this.
I want to get a view (with views_calc), with a table that adds a given number field giving separately the subtotal for each group of nodes.

I desire obtain the sum of values in a given field, separating the subtotal for each content type grouping they belong.

I appreciate the cooperation of the members of the forum.

Sorry for my English


Aren Cambre’s picture

Title: RELATED QUESTION » Add grouping support for views calc

Please start a new issue for new questions.

akolahi’s picture

I'm not sure if this is helpful, but perhaps to help prevent reinventing the wheel, it may be worth mentioning that the Charts module ( is able to perform the following operations from views groupings: sum, count, average, minimum and maximum. The user provides the grouping field, the operation, the field to perform the operation and the field to aggregate the results on. Works well with views.

Perhaps the code may be helpful in getting similar functionality into views calc. Just a thought.

doknet’s picture


seabrawk’s picture


its a views patch, so obviously its not a supported thing, but if you NEED it:

The fix in #29 did exactly what I needed...

tteller’s picture


tteller’s picture

Hi JamieR,

I think your solution would be a good workaround. I've done what you've said, but thinking about it how do I get the Sum row with your calculations?

I have a computed field that the value is generated from the CCK content creation page (form) and stored into my database as field_rip_points. I'm displaying them as a column in my View. Summing them is the problem for each user.

How do I create the Sum row? Or is that what the CSS wizardry you have to do? Oh, and do I create a new content type to hold the value of the summed field_rip_points?

Thanks in advance.
Tim T

mansspams’s picture


browlands’s picture


mansspams’s picture

use latest dev versions of views 3 and ckk 3 to get what you need now

patrickfrickel’s picture

Did what you suggested and found out that views 3 is only for Drupal 7. heart breaking false hope.

akolahi’s picture

I think there is a views 3 for drupal 6 as well. Did you look on the views project page?

calbasi’s picture

Yes, there is a Views v.3 but it is an alfa version: Not recommended for productive sites :-(

iSheng’s picture

I want to know the solution too

jackfoust’s picture

Regarding the problem in #4 that was mentioned being resolved in #12, how do I make this work? I am at 6.x-1.3, but still seeing the grand total sum being printed on each sub total sum line.

bobgeier’s picture

Same problem as jackfoust. This thread is very hard to follow because of the multiple issues; was there a solution other than the theme function kludge?

rlnorthcutt’s picture

This is great, and I have it working... but the code you post doesn't print anything except "none"... I have been able to get it to print the $data of the field, but can't get a total.



truyenle’s picture



bsztreha’s picture


Murz’s picture

Can I get not total, but per group values of views calc with module?

basvredeling’s picture

I created a patch for views_calc to get grouping to work. So no more theme-based work-arounds or patching of the views core.

Please note that I also applied this patch:

peterparker’s picture

I am trying to use the patch in #48 but it appears to end unexpectedly in the middle of a line.

basvredeling’s picture

Did you apply the patch to the latest dev? I tried it just now with a new checkout of cvs /contributions/modules/views_calc [HEAD] using eclipse. Worked flawlessly.

peterparker’s picture

I did. I might be uneducated about patches and how they work, but when I look at the file linked above it ends in the middle of a foreach statement. Am I missing something or is it normal for a function to end without closure?

steel-track’s picture

I just patched the latest dev version and I am getting the following error and no calculations:

warning: Invalid argument supplied for foreach() in [installation location] on line 188

Any idea what might be going on?



basvredeling’s picture

@peterparker The patch only describes which lines are altered. The ones with + and - signs at the start are the only lines that actually are written to the patched file. In other words: the patch doesn't need to "end with closure" because the closure is in the patched file. And that closure remains as it was before patching.

@steel-track line 188 in which file?

peterparker’s picture

I got the patch to work, thanks for the primer.
Tested it and got an error on line 188 of the, presumable just like steel-track.
I took a look and found a $$ which looked out of place (things looking out of place is the limit of my knowhow for the moment). Then again changing that and clearing the caches didn't help.

basvredeling’s picture

The data passed to the foreach statement is probably empty. Are you sure you created a views_calc view using at least 1 calculation? And are you sure you've grouped the view?

To avoid the error try wrapping the foreach statement running from line 188 to line 225 into an if ($$process) or an if (is_array($$process)) so that it reads:

        if ($$process) {
          foreach ($$process as $num => $row) {
            $type = '';
            foreach ($row as $item) {
              if (in_array($item, array_keys(_views_calc_calc_options()))) {
                $type = $item;
            if (!empty($row->$field_alias) || (isset($row->$field_alias) && $row->$field_alias === 0)) {

              // COUNT is always a numeric value, no matter what kind of field it is.
              if ($type == 'COUNT') {
                $vars[$process][$type][$column] =  $row->$field_alias;
              // Calculations other than COUNT should run the value through the field's theme.
              // This will allow dates and numeric values to apply the right formatting to the result.
              else {
                $vars[$process][$type][$column] =  $fields[$field]->theme($row);
            elseif (!empty($type)) {
              // Add the calc type label into the first empty column.
              // Identify which is the sub total and which the grand total
              // when both are provided.
              if (empty($added_label[$type])) {
                if ($process == 'sub_totals') {
                  $label = t("Page !Calculation", array("!Calculation" => $type));
                else {
                  $label = t("Total !Calculation", array("!Calculation" => $type));
                $vars[$process][$type][$column] = $label;
                $added_label[$type] = TRUE;
              else {
                $vars[$process][$type][$column] = '';
peterparker’s picture

I am in fact using a grouping field and am performing at least one calculation. I also tried performing a count on all of the fields too.

I made the changes recommended in #55 and the errors have gone away, but the view does not display any calculations.

steel-track’s picture

I can maybe take a look at it more myself over the weekend, but it's good to hear I'm not the only one with the issue.

But yeah, I am experiencing the EXACT same issue as peterparker. I have grouped and done a calculation, and yet I am getting that error and no calculations made.

Maybe it's an issue with what we are grouping by? I am grouping by a timestamp that I am changed to have a granularity of month in the field settings. What are you trying to group and calculate peterparker?

peterparker’s picture

I am grouping by date field and am trying to calculate the sum of decimal fields.

steel-track’s picture

I have read that some people have had issues running SUM on decimal fields in Views Calc, so that mightbe a different issue.

However, if you are using a date as well to group, that might be the key to this issue. Maybe there is some sort of issue with gauging granularity of each group?

basvredeling’s picture

If you folks could export the problem into a feature, and mail me the feature (or attach it to this thread). Then I can try debugging it.

basvredeling’s picture

Status: Active » Needs work
askibinski’s picture

I can confirm the patch at 48 works with one small fix. See new patch included.

In patching

$totals = $group_totals[$current_group];

Should be:

$totals = $view->group_totals[$current_group];

Note: I didn't need the patch at #776848: Calculate subtotals for non-node views, e.g., Ubercart orders.

basvredeling’s picture

Status: Needs work » Needs review

Thanks for the addition askibinski. Patch seems to work as meant.

Tokoh’s picture

Thanks everyone for the work on the view calc module. I have been trying to get grouped totals for my app and the patch at #48 and its minor amendment worked, with the problems cited with respect to foreach warning problems if no sums are included.
However as I introduced more data I realised that I need to use the View's pager feature and unfortunately it broke the patch (maybe it also doesn't work with unpatched view calc but I haven't tried this). With the pager feature invoked each group total (say called a TOTAL SUM in bold) is preceded with a new total (say called a Page SUM in normal text) which in fact is the grand total of that column for the application. Furthermore the pager links do not appear at all at the foot of the page and consequently you cannot access pages past the first page.
Although I'm an experienced programmer, I'm still pretty new to Drupal and to PHP. But I need this problem fixed as grouping and totaling are critical to my application. I will spend as much time as it takes to fix this problem, but I'd be interested in hearing from others who might be grappling with/have solved this problem.

I think view calc is a really vital module for Drupal Views and would hate to resort to custom code when others can leverage off this initiative, but I'm interested to hear other views.

basvredeling’s picture

I don't really like the grouping solution I posted above. After giving it some thought I reckon the best way to rewrite the grouping support is actually run completely different queries. The way the grouping support works now is actually a loop of the normal views_calc calculations. This results in a couple of empty tables with just a "total" row. What we'd like instead is a single table with the grouped results on each row and a total row at the bottom. It would require a complete rewrite of the grouping patch and probably a partial rewrite of the module. The "grouping" check should be earlier in the process, before the database is queried. And not in the, where it currently resides.

miro_dietiker’s picture

Status: Needs review » Needs work

Some rework happened in the core of views_calc. It should be some cleaner now.

I'll open a views 3 branch soon. Due to the new features and current dev state i'd expect something like grouping will officially not be supported by views_calc with views 2.

If you like to push this feature, check views 3 capabilities and start helping us port things cleanly to views 3.

Inky3d’s picture

Thanks! The patch in 48 with 62's update works for me.

jhodgdon’s picture

Status: Needs work » Needs review
8.08 KB

Ah, I wish I had seen this issue...

Here's another patch for Views 2, which adds support for grouping. It works well for me... It also adds some additional theming capability, so you can theme the label of the summary rows.

It takes a slightly different route than the patches above.

I am not yet using Views 3, and when I tried migrating to Views Calc 3.x-dev and Views 3.x-dev, the views I am using completely didn't work even as a starting point, so I'm not all that interested in working on the 3.x port at this time...

Anyway, maybe this patch will be useful to someone, and maybe you'd consider adding it to the 1.x branch so at least grouping would be supported.

jhodgdon’s picture

2.82 KB

Somehow the change for didn't make it into the last patch. So this additional patch needs to be applied... still getting the hang of the git workflow... sorry!

acouch’s picture

I tried a different approach to this for Views 3.x, performing calculations on the field output instead of using SQL, that might be useful for some folks. Let me know if you have any thoughts or feedback:

ayalon’s picture

Attached you find a patch working with Views 3 and 6.x-3.x-dev ViewsCalc.
Diesplaying of Subtotal for each group is possible.Based on #69

pragnatek’s picture

@jhodgdon: can't get your patch to apply to:

patching file
Hunk #1 FAILED at 10.
Hunk #2 succeeded at 18 (offset -2 lines).
Hunk #3 succeeded at 33 (offset -2 lines).
Hunk #4 succeeded at 44 (offset -2 lines).
Hunk #5 succeeded at 59 (offset -2 lines).
Hunk #6 FAILED at 83.
Hunk #7 FAILED at 96.
Hunk #8 FAILED at 114.
Hunk #9 FAILED at 165.
Hunk #10 succeeded at 187 with fuzz 2 (offset -10 lines).
Hunk #11 FAILED at 197.
Hunk #12 succeeded at 229 (offset -24 lines).
Hunk #13 FAILED at 243.
7 out of 13 hunks FAILED -- saving rejects to file

applied to views_calc 6.x-1.3.

Any ideas - I'd like to try this? Thanks

jhodgdon’s picture

Sorry, I gave up on Views Calc with grouping. It doesn't work well with calculated fields from other modules, and that's what I needed. So I ended up creating a simpler table with column sums views style plugin that works better for my purposes. If anyone's interested, post here... it should be up on d.o in a sandbox as soon as I can figure out Git, and I can post a link (although the sandbox project will have several other components to it).

The patches above were against the 6.x-1.x dev branch, not against 6.x-1.3 specifically, so that could be why they don't apply, or maybe the dev branch has been updated since I made the patch.

pragnatek’s picture

@jhodgdon: thanks for the update and yes, of course, we'd be interested to see your dev solution up on d.o. Thanks

jhodgdon’s picture

This is the sandbox project I set up, which has my "add up a column in a table" views style plugin as part of it:

pragnatek’s picture

@jhodgdon Thanks for sharing this.

k3n3dy’s picture

#68 and #69 worked for me.
Drupal 6.22
Views 6.x-2.12
Views Calc 6.x-1.x-dev (2011-fev-25)

MBroberg’s picture

#68 and #69 worked for me when details are showing but not when I hide the details and want just the group results.

sdsheridan’s picture

Re. #62, I had to make a couple of small alterations to the code in after applying the patch to 6.x-1.3 to get it working. Not sure if these things had already been done in the -dev version at the time this was being discussed, but... Both of the changes were to the function query_sub_total as follows:

  1. Empty the "Order By" element of the query object - I was getting the same error in cited in #52 when sorting, which resulted in no subtotals. It seemed to be related to an "unknown column" error in the "order by" clause of a query. I'm not sure where the odd column name is arising (I am using two relationships in the view in question, so clearly something is getting muddled in the column name construction), but it struck me that for this function, the "order by" clause was kind of useless given the query that was being constructed. So, I inserted $this->view->query->orderby = array(); after the code that also cleared the fields array. This made my unknown column issue go away.
  2. Remove duplicate WHERE clauses - Further down in the same function I noticed that the patched was inserting a line to ostensibly deal with relationships and what was the true base table and base field instead of just assuming it was node.nid, but the line above it hadn't been commented out, thus having both limiting clauses in the WHERE clause. So, I commented out that line.

The result is the function below:

  function query_sub_total() {
    // Create summary rows.
    $calc_fields = $this->get_calc_fields();
    $calc = $this->view->views_calc_calculation;
    $fields = $calc_fields[$calc];
    // Empty out any fields that have been added to the query,
    // we don't need them for the summary totals.
    $this->view->query->fields = array();
    $this->view->query->orderby = array();   //  <-- clear out the ORDER BY clause that was causing "unknown column" errors
    foreach ($this->view->field as $field) {
      $query_field = substr($field->field, 0, 3) == 'cid' ? $field->definition['calc'] : $field->table .'.'. $field->field;
      $query_alias = $field->field_alias;
      if (in_array($field->field, $fields)) {
        // Calculated fields.
        $this->view->query->add_field(NULL, "$calc($query_field)", $query_alias);
        $this->view->query->add_table($field->table, NULL, NULL, $field->table);
      else {
        // Empty fields that have no calculations.
        $this->view->query->add_field(NULL, "MAX('')", $query_alias);
      // Add a dummy field for the groupby.
      $this->view->query->add_field(NULL, "MAX('". $calc ."')", "TOTAL_". $calc);
    // TODO This won't work right with relationships, need a fix here.
    if (!empty($this->view->views_calc_nids)) {
//      $this->view->query->add_where(NULL, "node.nid IN (%s)", implode(',', $this->view->views_calc_nids));   // <-- this was 'corrected' by the following line in the patch, and so should be removed, no?
      $this->view->query->add_where(NULL, "%s.%s IN (%s)", $this->view->base_table, $this->view->base_field, implode(',', $this->view->views_calc_nids));

I'm now getting group sub-totals with correct sub-totals. Unfortunately, the overall totals are not showing up... anyone else experiencing that problem?


westie’s picture


Delty’s picture

I attempted to use the patch in #71. It applies to the 3.x dev version OK, and I get the subtotal rows in the view, but nothing is calculated. I don't get any errors either. Had anyone else tried the 3.x dev patch and were you able to get it working?


daniels____’s picture


frishaynes’s picture

Version: 6.x-1.x-dev » 7.x-1.0
14.65 KB

I managed to port #71 to version 7.x.1.0 and attached the modified files to display group totals. :)
I'm sure it can be refined as I just made it work, especially line 323 as I don't fully understand how the theme() function works in this context.

portulaca’s picture


Sinan Erdem’s picture

126.16 KB

I tested the files on #83. They work as desired if you do only one grouping. If you select another grouping field (Grouping field Nr.2), the fields are not displayed correctly.

petednz’s picture

Can anyone confirm if the patch in #83 has been committed at all?

I see the 'dev' release is showing as older than the released version which has me scratching my head.

Thanks for any updates.

Reason for asking is I want to use 'grouping' on a Calc Table such that the sub-total for that grouped set of rows shows - whereas currently it gives me a Total row on each Grouping of results, but that Total shows the Total for all results, not just those that are 'grouped'

Sounds like #83 is what I might need

petednz’s picture

Just to confirm - i used the files supplied in #83 and updated my Views Calc module with them - and hey presto i have a Total row for my Groupings that is only summing those rows - plus an extra Total at the bottom of the last Grouping with the grand total.

Not sure if that counts as 'reviewed by community' - but it is doing what I expected at least for Sums. Thanks @ frishaynes and ayalon and others who may have contributed earlier in the ticket.

Can/should this be committed?

Andrew Edwards’s picture

I can confirm (as per #85) that there is a problem with the files on #83.

All works well if using only 1 grouping. Works with pagination too, which is great!

Using 2 groupings breaks things though. Tables lose all of their values (each table cell is empty). The extra tables that should be created for the second grouping do not appear.

adamtong’s picture

I can confirm the #83 is working well on only 1 grouping. if more than 1 grouping, the situation is the same as #88.

fmesco’s picture

Version: 7.x-1.0 » 6.x-1.3

The views style plugin in the sandbox project from #75 worked like a charm...Gave me sub-totals by group and then a grand total at the bottom. I just wish there was a way to include it in the views_calc or even regular views module, because I really don't need all the other modules that you have to install to use it.

Drupal 6.28
Views 6.x-2.16

hallg9999’s picture

#83 - Thanks for sending out the attachment. Now I can total Views with group fields. One thing to note is that the label "Total" does not specify the calculation type (i.e., Total Sum, Total Avg, etc.). This can easily be fixed my modifying the theme.ini file. On the "views_calc_table_total" function, concatenate the Total label with the $calc variable (contains the type of calc):
$Total_and_Calc = "Total" . ' ' . $calc;
$label = t($Total_and_Calc, array("!Calculation" => $calc));

hallg9999’s picture

This patch is in response to #83. Ability to group field and also displays the Total labels (i.e., Total AVG). In #83 you can group by one field, but the type of calc label was not displaying. This patch also fixes the label issue.

hallg9999’s picture

rhclayto’s picture

#92 works for me. I applied the patch manually. Cheers!

jiakomo’s picture

I am getting errors applying #92 to current -dev

jason.fisher’s picture

Probably related to the patch altering CHANGELOG.txt?

deejmer’s picture

I'm in pretty critical need of grouped totals, but I am getting errors applying #92 to current -dev as well.

I attempted to apply it manually like rhclayto did, but found it too difficult as i'm a newb with patching. Maybe @rhclayto, you can share your entire views_calc directory including the patched files themselves that I can simply deploy out to my site?

I'm stunned this hasn't been applied to the main module yet as it seems like basic functionality.

@hallg9999, maybe you could update your patch to work against the latest dev?

Thanks in advance...

KarenS’s picture

Issue summary: View changes
Status: Needs review » Closed (won't fix)

The D6 version is no longer supported.

rhclayto’s picture

Version: 6.x-1.3 » 7.x-1.x-dev
Status: Closed (won't fix) » Reviewed & tested by the community

Since 6.x is no longer supported, & this functionality is still not included in the 7.x branch as far as I am aware, & the patch in #92 is for 7.x & works for me, I am changing this to 7.x-1.x & marking as RTBC. It would be great to have this added.

rhclayto’s picture

Status: Reviewed & tested by the community » Needs review
8.33 KB

Adding a patch for the latest 7.x-1.x-dev cloned from git. This is based on the patch at #92, which did not apply cleanly: it looks like that patch was based on 7.x-1.0, & also had a lot of extra stuff, looks like it was made against an already patched 7.x-1.0.

In addition, I've added the ability to have the totals label for grouped totals specify 'subtotal' or 'total' depending on whether it is a group total or the final total, & also maintain the ability to have the label 'page total' for paged views, which was lost with the patch at #92.

Note: This does not apply against the dev version I downloaded in the gz archive on the project homepage as of 3:35Am, 16 February 2014.

Please review & hopefully this can get committed, since it's an important functionality that has been desired since 2007!

rhclayto’s picture

An issue I found: When using this patch with a view of pager type 'none' (Display all items'), the 'Page' total labels usually displayed on paged outputs will display on every group (with blank values, since it's not really paged). I isolated where the problem lies & made a quick fix.

In, within function template_preprocess_views_calc_table(&$vars), I made the following change (commented line is original, following line is the fixed one):

//if ($view->query->pager->get_total_items() > $view->get_items_per_page()
  if ($view->query->pager->plugin_name != 'none' && $view->query->pager->get_total_items() > $view->get_items_per_page()

This simply checks if the pager is 'none' (views_pager_plugin_none). If so, it skips the Page subtotals.

Uwe Mindrup’s picture

I have tested #100 and #101 together with the git-version of views_calc from today and can say, it works very fine! I have a big table with several number columns grouped by classes. The results page shows my tables wonderful with a subtotal SUM at the end of every group-table and a Total SUM line at the end of the last table. Very good! It is exactly what I need.

It would be great to have this functionality in the next views_calc release.

rhclayto’s picture

Status: Needs review » Reviewed & tested by the community

Uwe, great that it works for you. Since the patch I supplied is really just a re-roll of the patch at #92 to get it to apply cleanly to the current dev (with a couple simple extras), & that version has been tested & found to work by several people, I will mark this as RTBC.

AndreasST’s picture

56.88 KB

I applied #100 and #101 manually to 7.x-1.x-dev from Feb 15th 2014

In a view i added submitted fields from a webform and added a computed field ([erreichte_ringe]/[zu_erreichende_ringe])*100 - see screenshot.

I only get wrong an no calculations on SUM, AVG, ...
The wrong calculations where there before applying the patch.

I get an error:
Notice: Undefined property: stdClass::$nid in views_calc_table->calc_group_totals() (Zeile 341 von /xxxx/
Line 341 is: $ids[] = $value->$field; in following piece of

  function calc_group_totals($sets) {
    $field = $this->view->base_field;
    $this->view->group_totals = array();
    foreach ($sets as $set) {
      $ids = array();
      foreach ($set as $value) {
        $ids[] = $value->$field;
      $this->execute_summary_view($ids, TRUE);
scott.browne’s picture

Works amazingly with 100 thank you rhclayto and the others whom did this.

You should update that with the live asap.

This just went from an average module to a very awesome module!

Thank you for your update and work.

scott.browne’s picture

The pager section:

Display all items adds an error:

Notice: Undefined property: stdClass::$field_data_field_name_add_node_entity_type in views_calc_table_total() (line 311 of /

It goes away by picking anothe pager option. I'm not sure if that is an easy patch but still works going the other route for me.


Niremizov’s picture

Unfortunattely patch #100 does not work with view aggregation enabled.

One of the possible reasons of this error: "Notice: Undefined property: stdClass::$nid in views_calc_table->calc_group_totals()" - is that views_calc uses base_field to execute summary query (base field used as filter for aggregated summary query). In previous versions of Views module base field was included automatically in each view.
There is one more reason to refuse using base field, this reason is aggregation. To summarize already aggregated view we must use a subquery.

Niremizov’s picture

Status: Reviewed & tested by the community » Needs review
14.36 KB

So here is the patch that is based on #100 and Patch supports subtotals and grouping with or without aggregation by using subquery.

I suppose that further code refactoring is needed.

Niremizov’s picture

Niremizov’s picture

Here is new patch. Now subquery used for every request (cause it is more stable even for hardcoded views), some code clean up was made. There still some redundant code left.

Pierre.Vriens’s picture

To whom it may concern: maybe consider a new approach using module forena to address various topics in this interesting issue? For more details checkout the various documentation links mentioned on the project page.

jcam88’s picture

Would be great if this patch also worked when the "Show Details" selection was set to "No". -- Select 'Yes' to show detailed values followed by column calculations, 'No' to suppress details and show only calculated column totals.

dbassendine’s picture

Adding a patch for (very old) 6.x / Views 2 that implements the fix for #62 in #79 point number 2.

dbassendine’s picture

Update for #113 - patch did not apply.

CandC540’s picture

#110 did not work for me. I ended up using jQuery to solve the problem for now. I'm posting this in hopes that it may help someone else out. The source that I adapted my code from was found here: Drupal 7: jQuery and Subtotaling Views Calc Tables

The only problem is that parseFloat() doesn't work when you're using a comma for the thousands separator, so I ended up having to remove commas and added them back after the subtotal was calculated.

(function ($) {
  Drupal.behaviors.subTotal = {
    attach: function(context) {
      //run only if there is a context var
      if(typeof context !== 'undefined'){	
  var PTSum = parseFloat(0);
  //Replace .view-production-totals with the class for your view
  $('.view-production-totals .views-table').each( function() {

  PTSum = 0;

  //I used tbody here, because the .views-field-field-production-total class was also
  //used for the total sum in the views table, and I didn't want it adding the page total
  //to my subtotal. Replace .views-field-field-production-total with the CSS class of the
  //field you want to get a subtotal for.
  $('tbody .views-field-field-production-total p', this).each(function(){

  //Remove all thousands separators. In this case we are replacing commas
  PTSum += parseFloat($(this).html().replace(",",""));

  //Add Comma Separators
  PTSum = PTSum.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  //Update the Total Sum. Replace .views-field-field-production-total with the field's CSS class
  $('tr.view-footer-number:contains("Total SUM") .views-field-field-production-total', this).html(PTSum);

I then used JS Injector to add the script to my site.

dobrzyns’s picture

Since this issue is marked as version 7.x-1.x-dev please only add patches for Drupal 7. Once the patch has been committed for Drupal 7, a patch for version 6 can be developed.

I've reviewed and tested the patch from comment 110. I've also verified that it does not break when aggregation is turned on, aggregation is probably redundant now. Although there is still some redundant code, the patch does work. Unless someone is willing to take on eliminating redundant code (making this DRY), I recommend it be committed. I say this knowing that the focus now is on Drupal 8 and that will be de facto relatively soon.

dobrzyns’s picture

Status: Needs review » Reviewed & tested by the community
Kleinast’s picture

#110 Work well with classic number but not with price field.

big_smile’s picture

I am having the same problem as Kleinast (in #118). My price field is of field type "float". Views Calc displays the total as 0.00.

kristofferwiklund’s picture

Status: Reviewed & tested by the community » Needs work

Does not work with latest stable or dev version.

Ahmad Kharbat’s picture

I have a related issue that I'm attaching a screenshot for. A General Ledger for Jornal entries (transactions) Grouped By account. I'm trying to acheive one of two possible solutions

1- Either display Total SUM per group correctly. (right now each groups displays the total of the whole page)

2- Or remove the Total SUM from each group, and just keep it at the end of the page.

#110 Didn't work for me, the Total SUM always displays Zero. I have a float field

I will see if i can resolve this and include a patch. Any suggestions or workarounds will be appreciated.


delacosta456’s picture

hi @kharbat

i am having zero too .. whatever i tried

have you found a solution please?