title: Find last row in group by query-SQL Server
body: <p>I have table in SQL Server. I want to find last row in each group. I tried with the following query, but it does not return exact result. ID column is PK and other columns are set to NOT NULL.</p>
  
  <pre><code>select ID, Name FROM 
  (select ID, Name, max(ID) over (partition by Name) as MAX_ID
  from Customer) x where ID= MAX_ID
  </code></pre>
  
  <p>To be more clear. I have 2 queries.First:</p>
  
  <pre><code>ALTER PROCEDURE [dbo].[Ramiz_Musterija_RowNum]
  @Datum DATE,
  @BrojKamiona INT
  AS SET NOCOUNT ON
  SELECT Ime,MusterijaID,RowNum=ROW_NUMBER() OVER(ORDER BY Ime)FROM Musterije
  WHERE Datum=@Datum AND BrojKamiona=@BrojKamiona  GROUP BY Ime,MusterijaID
  </code></pre>
  
  <p>And second one: </p>
  
  <pre><code>ALTER PROCEDURE [dbo].[Ramiz_Musterija_FindLast]
  @Datum DATE,
  @BrojKamiona INT
  AS SET NOCOUNT ON
  SELECT a.* from Musterije a
  JOIN (SELECT Ime, MAX(MusterijaID) AS MAXID FROM Musterije GROUP BY Ime) AS b 
  ON a.MusterijaID = b.MAXID AND a.Datum=@Datum AND a.BrojKamiona=@BrojKamiona
  </code></pre>
  
  <p>Then LINQ query:</p>
  
  <pre><code>  var rowNumList = from f in customerFindLastList
                       join r in customerRowNumList
                       on f.MusterijaID equals r.MusterijaID
                       select new { r.RowNum };
  </code></pre>
  
  <p>I am trying to find last row in each row,then match this 2 queries on MusterijaID column.
  Any help regarding this would be appreciated.
  This is output of one group. Now, problem is that these two queries are matched on "4250" MusterijaID, but I need to match queries on "4229".</p>
  
  <pre><code>Ime MusterijaID
  100//1  4246
  100//1  4247
  100//1  4248
  100//1  4249
  100//1  4250
  100//1  4229
  </code></pre>