<p>I haven't tested this, but I think <code>.sum()</code> will execute your query, so put it at the end:</p>
<pre><code>{% set reimbursementAmount = craft.matrixBlocks()
  .relatedTo(cat)
  .fieldId(9)
  .specialCase(':empty:')
  .sum('field_item_reimbursementAmount')
%} 
</code></pre>

CC BY-SA 4.0
2020-09-04T22:52:50.410Z
Thanks, ended up using a Twig loop to SUM the values.
4midori
CC BY-SA 4.0
2020-08-27T07:10:44.177Z
2020-08-27T07:10:44.177Z
James Smith
<p>I have some Matrix blocks where I need to sum one of the fields within, but I only want to sum it when another field within that block is or is not empty.</p>
<pre class="lang-twig prettyprint-override"><code>{% set reimbursementAmount = craft.matrixBlocks()
  .relatedTo(cat)
  .fieldId(9)
  .sum('field_item_reimbursementAmount')
  .specialCase(':empty:')
  %} 
</code></pre>
<p>With this, I get an error:</p>
<p><strong>Impossible to invoke a method (&quot;specialCase&quot;) on a string variable (&quot;101.00&quot;).</strong></p>
<p>How do I sum the desired field, but only where another field (specialCase) is empty (or is not empty, as the case may be).</p>

<matrix><query>
Problem with SUM on Matrix blocks
# Problem with SUM on Matrix blocks

(Asked by: username_0 on 2020-08-26)

I have some Matrix blocks where I need to sum one of the fields within, but I only want to sum it when another field within that block is or is not empty.
{% set reimbursementAmount = craft.matrixBlocks()
  .relatedTo(cat)
  .fieldId(9)
  .sum('field_item_reimbursementAmount')
  .specialCase(':empty:')
  %} 

With this, I get an error:
Impossible to invoke a method ("specialCase") on a string variable ("101.00").
How do I sum the desired field, but only where another field (specialCase) is empty (or is not empty, as the case may be).

**Tags:** matrix, query


---

## 1 answers

### Answer by username_1 on 2020-08-27. Score: 1

I haven't tested this, but I think .sum() will execute your query, so put it at the end:
{% set reimbursementAmount = craft.matrixBlocks()
  .relatedTo(cat)
  .fieldId(9)
  .specialCase(':empty:')
  .sum('field_item_reimbursementAmount')
%}

> **Comments:**
> **username_0**: Thanks, ended up using a Twig loop to SUM the values.  

---

