title: Using Having Sum with Linq to SQL
body: <p>I have a SQL command that I am trying to convert to a LINQ to SQL command, but am having difficulties.</p>
  
  <p>My SQL command follows:</p>
  
  <pre><code>SELECT purchs.iclientid, ifeatureid, AddnlOptionList FROM purchs
  WHERE AddnlOptionList &lt;&gt; ''
  GROUP BY purchs.iclientid, ifeatureid, AddnlOptionList
  HAVING (SUM(noptions) &gt; 0)
  </code></pre>
  
  <p>I've managed to get this far following examples:</p>
  
  <pre><code>var q =
     from purchs in db.Purchases
     group q by purchs.noptions into g
     where purchs.AddnlOptionList != ""
        &amp;&amp; g.Sum(x =&gt; x.noptions) &gt; 0
     select q;
  </code></pre>
  
  <p>However, I seem to be stuck on group q with the following two errors:</p>
  
  <pre><code>Cannot use local variable 'q' before it is declared
  
  Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer&lt;decimal?&gt; because it is not a delegate type
  </code></pre>
  
  <p>An example from <a href="https://stackoverflow.com/questions/20318380/sql-query-in-linq-with-having-sum">here</a> says that this should work, although it uses a join, and I am not. Any help would be appreciated.</p>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>I had to modify Xiaoy312's code a little bit to get what I wanted, so I figured I would post it here in hopes that it might help someone in the future. Thank you @Xiaoy312 for the help.</p>
  
  <pre><code>var updates = db.Purchases
     .Where(p =&gt; p.AddnlOptionList != "")
     .GroupBy(p =&gt; new { p.iclientid, p.ifeatureid, p.AddnlOptionList })
     .Where(g =&gt; g.Sum(p =&gt; p.noptions) &gt; 0)
     .Select(g =&gt; g.Key);
  </code></pre>