title: SQL Server CREATE AGGREGATE logic error
body: <p>I've created a CLR funtion for SQL Server 2014 that should calculate subtraction between the first and the last value in column <code>[Value]</code>.</p>
  
  <p>Here is the table:  </p>
  
  <pre><code> Date_Time                    Value
   -------------------------------------
   2018-03-29 09:30:02.533      6771
   2018-03-29 10:26:23.557      6779
   2018-03-29 13:12:04.550      6787
   2018-03-29 13:55:44.560      6795
  </code></pre>
  
  <p>Here is the code:  </p>
  
  <pre class="lang-cs prettyprint-override"><code>using System;  
  using System.Data;  
  using System.Data.SqlClient;  
  using System.Data.SqlTypes;  
  using Microsoft.SqlServer.Server;  
  
  [Serializable]  
  [SqlUserDefinedAggregate(Format.Native,  
                           IsInvariantToDuplicates = false,  
                           IsInvariantToNulls = true,  
                           IsInvariantToOrder = false,  
                           IsNullIfEmpty = true,  
                           Name = "SUBT")]  
  public struct SUBT  
  {  
   private double first;  
   private double last;  
   private int count;  
  
   public void Init()  
   {  
        first = 0.0;  
        last  = 0.0;  
        count = 0;  
   }  
  
   public void Accumulate(SqlDouble Value)  
   {  
      if (!Value.IsNull)  
      {  
          if (count == 0) 
              first = (double)Value;
          else 
              last = (double)Value;
  
          count += 1;  
      }  
   }  
  
   public void Merge(SUBT Group)  
   {  
      first = Group.first;
      last = Group.last;
      count += 1;  
   }  
  
   public SqlDouble Terminate()  
   {  
        double value = (double)(last - first);  
        return new SqlDouble(value);  
   }  
  }  
  </code></pre>
  
  <p>So the result should be <code>[Value]=24</code>, i.e. 6795 - 6771, but I get 6795 :(  </p>
  
  <p>Where is the error?  </p>