title: SQL Server - SUM Function giving Subquery returned more than 1 value. This is not permitted when the subquery follows
body: <p>I simplified the example below,  it is actually part of a larger query,  so I do need to restrict the sum call as it's part of the select clause in a larger query I'm building. </p>
  
  <p>I've done some searching on this but am still confused. I'm a developer and not a SQL guru so I could be missing something obvious but I'm fairly perplexed.</p>
  
  <p>In terms of pseudo code, what I would be trying to do is this:</p>
  
  <p>Assume I have a collection of objects that match the base query (so, records that match the clause <code>where field4 = '1111' and field2 = '201510'</code>.</p>
  
  <p>Then I iterate through each of these, and, using the value from the current record, I want to perform the sum function:</p>
  
  <pre><code>(SELECT SUM(ISNULL(t1.field3,0)) 
   FROM table1 
   where field1 = t1.field1 and field2= t1.field2) SummedValue
  </code></pre>
  
  <p>I envision it "looping through" and doing a SUM, with each, so, for example, if in one of these iterations it has a vale of <code>field1 = '3433'</code> and <code>field2='201510;</code>, then it would SUM all records from <code>field3</code> that match this, however I get the error:</p>
  
  <blockquote>
    <p>Subquery returned more than 1 value. This is not permitted when the
    subquery follows =, !=, &lt;, &lt;= , >, >= or when the subquery is used as
    an expression.</p>
  </blockquote>
  
  <p>This is the SQL I'm using:</p>
  
  <pre><code>SELECT
  distinct
  (SELECT SUM(ISNULL(t1.field3,0)) FROM table1 where field1 = t1.field1 and field2= t1.field2) SummedValue,
  t1.field1,
  t1.field2
  from 
  table1 t1 where field4 = '1111' and field2 = '201510'
  GROUP BY t1.field1, field2
  </code></pre>
  
  <p>I think I'm misunderstanding something, would appreciate any advice on what I am doing wrong. Thanks</p>