title: Selecting one distinct column, I.E Finetuning select query
body: <p>I use the bellow query to merge 1 (or possibly sevral tables and is generated from a php script I have written) on Id's that are not the same but parts of Id in first table is part of the second Id so thats why I do a Substring on it. In the most perfect world I would just left join on id in both tables if there were the same but they're not.</p>
  
  <pre><code>select t0.Id,t0.CustomerName,t0.Region,t0.Country,t0.StopTime,t0.CustomerId,t1.Id, t1.Time
  from (select distinct Id,CustomerName,Region,Country, StopTime,CustomerId from [dbcust].[dbo].[_Content]) t0 
  Inner JOIN 
  (select distinct Id, Time from [dbcust].[dbo].[_Cpu]) t1 
          on SUBSTRING(t1.Id,CHARINDEX('_',t1.Id,10)+1,(CHARINDEX('_',t1.Id,15) - CHARINDEX('_',t1.Id,10)-1))=SUBSTRING(t0.Id,CHARINDEX('_',t0.Id,10)+1,(CHARINDEX('_',t0.Id,15) - CHARINDEX('_',t0.Id,10)-1)) ORDER BY t1.Time DESC
  </code></pre>
  
  <p>Here I get Alot of fields that are the same except for StopTime, see example bellow: </p>
  
  <pre><code>       StopTime                   Time
  2015-04-01 23:59:00.000    2015-04-18 23:00:01
  2015-04-02 23:59:00.000    2015-04-18 23:00:01
  2015-04-03 23:59:00.000    2015-04-18 23:00:01
  2015-04-04 23:59:00.000    2015-04-18 23:00:01
  2015-04-05 23:59:00.000    2015-04-18 23:00:01
  2015-04-06 23:59:00.000    2015-04-18 23:00:01
  2015-04-07 23:59:00.000    2015-04-18 23:00:01
  2015-04-08 23:59:00.000    2015-04-18 23:00:01
  2015-04-09 23:59:00.000    2015-04-18 23:00:01
  2015-04-10 23:59:00.000    2015-04-18 23:00:01
  2015-04-11 23:59:00.000    2015-04-18 23:00:01
  2015-04-12 23:59:00.000    2015-04-18 23:00:01
  2015-04-13 23:59:00.000    2015-04-18 23:00:01
  2015-04-14 23:59:00.000    2015-04-18 23:00:01
  2015-04-15 23:59:00.000    2015-04-18 23:00:01
  2015-04-16 23:59:00.000    2015-04-18 23:00:01
  2015-04-17 23:59:00.000    2015-04-18 23:00:01
  2015-04-18 23:59:00.000    2015-04-18 23:00:01
  </code></pre>
  
  <p>But here I only want unique Time, is it possible to get a row with the unique Time and the latest StopTime?</p>
  
  <p>Like the bellow?</p>
  
  <pre><code>        StopTime                   Time
  2015-04-01 23:59:00.000    2015-04-18 23:00:01
  </code></pre>
  
  <p>I tried with a <code>group by</code> statement inside the second select statement like:</p>
  
  <pre><code>(select distinct Id,CustomerName,Region,Country, StopTime,CustomerId from [dbcust].[dbo].[_Content] group by StopTime)
  </code></pre>
  
  <p>But I get a syntax error</p>
  
  <blockquote>
    <p>Column 'dbcust.dbo._Content.Id' is invalid in the select list because
    it is not contained in either an aggregate function or the GROUP BY
    clause.</p>
  </blockquote>
  
  <p>Perhaps you guys can help me with finetuning my select query in order to speed up the data gathering? =)</p>
  
  <p>Thanks in advance.</p>