title: SQL Server 2008 Sum and Select Max Only?
body: <p>I am trying to understand how to do a Sum when I need to only use the Max/top values for a date period. This is kind of like <a href="https://stackoverflow.com/questions/7118170/sql-server-select-only-the-rows-with-maxdate">SQL Server: SELECT only the rows with MAX(DATE)</a> but not exactly. Thanks for reading.</p>
  
  <pre><code>declare @tbl Table ( tableid int , eventdate date,  valuec char(5) , valued int , recordedwhen datetime2(3) )
  insert into @tbl values ( 0 , '2012-03-22' , '11111' , 3 , '2012-03-23 17:21:01.083' )
  insert into @tbl values ( 1 , '2012-03-22' , '22222' , 3 , '2012-03-23 17:21:01.083' )
  insert into @tbl values ( 2 , '2012-03-22' , '22222' , 4 , '2012-03-23 18:21:01.083' )
  insert into @tbl values ( 3 , '2012-03-22' , '22222' , 5 , '2012-03-23 18:21:01.083' )
  
  select 
          eventdate, valuec , sum(valued) as valuedSum , recordedwhen
          from 
          @tbl
          group by eventdate, valuec, recordedwhen
  </code></pre>
  
  <p>I get three rows. But what I actually want is this:</p>
  
  <pre><code>--   
  --   eventdate  valuec valuedSum   recordedwhen
  --   ---------- ------ ----------- ----------------------
  --   2012-03-22 11111  3           2012-03-23 17:21:01.08
  --   2012-03-22 22222  9           2012-03-23 18:21:01.08
  </code></pre>
  
  <p>I do not want the row where tableid=1 because that is part of an older batch of data.
  The newer rows represent a later insert (all recordedwhen values with the same datetime are the same for a batch)</p>
  
  <p>So if a new row was inserted like this:</p>
  
  <pre><code>insert into @tbl values ( 4 , '2012-03-22' , '22222' , 6 , '2012-03-24 18:21:01.083' )
  </code></pre>
  
  <p>Then the data would should like this:</p>
  
  <pre><code>--   eventdate  valuec valuedSum   recordedwhen
  --   ---------- ------ ----------- ----------------------
  --   2012-03-22 11111  3           2012-03-23 17:21:01.08
  --   2012-03-22 22222  6           2012-03-24 18:21:01.08
  </code></pre>