Question: For every AbsenceBalance.AbsenceTypesUID I want to return the latest record AbsenceBalance.BalanceTime for each AbsenceBalance.EmployeeUID

I have tried select max but it only returns the most recent entry for the entire table and not by AbsenceBalance.AbsenceTypesUID or AbsenceBalance.EmployeeUID

This is my query

```
SELECT TOP (1000) 
AbsenceBalance.[UID],
AbsenceBalance.BalanceTime,
AbsenceBalance.AbsenceTypesUID,
AbsenceBalance.Mins,
Employee.FullName,
Employee.FirstName,
Employee.LastName,
AbsenceBalance.EmployeeUID,
absencetypes.LongName

  from [RiteqDB].[dbo].[AbsenceBalance]

  LEFT JOIN [RiteqDB].[dbo].Employee on AbsenceBalance.EmployeeUID = Employee.UID

  LEFT JOIN [RiteqDB].[dbo].AbsenceTypes on absencebalance.AbsenceTypesUID = absencetypes.UID 

  where AbsenceBalance.[UID] = (select max (AbsenceBalance.[UID]) from [RiteqDB].[dbo].[AbsenceBalance] where AbsenceBalance.AbsenceTypesUID = AbsenceBalance.AbsenceTypesUID)

  --where Select Max(v) from (values (AbsenceBalance.BalanceTime)

  order by FullName, AbsenceTypesUID

```

Answer: 
```
;with cte as (
SELECT TOP (1000) AB.[UID]
                 ,AB.BalanceTime
                 ,AB.AbsenceTypesUID
                 ,AB.Mins
                 ,E.FullName
                 ,E.FirstName
                 ,E.LastName
                 ,AB.EmployeeUID
                 ,AT.LongName
                 , ROW_NUMBER() OVER(PARTITION BY AB.[UID], AB.EmployeeUID order by AB.BalanceTime DESC) AS RUN
FROM [RiteqDB].[dbo].[AbsenceBalance] AB
LEFT JOIN [RiteqDB].[dbo].Employee E ON AB.EmployeeUID = E.UID
LEFT JOIN [RiteqDB].[dbo].AbsenceTypes AT ON AB.AbsenceTypesUID = AT.UID    
)
select * from cte
where RUN = 1

```
In your where condition your comparing with itself that might be the issue.

```
select max (AbsenceBalance.[UID]) from [RiteqDB].[dbo].[AbsenceBalance] 
where AbsenceBalance.AbsenceTypesUID = AbsenceBalance.AbsenceTypesUID

```

following is wrong

```
AbsenceBalance.AbsenceTypesUID = AbsenceBalance.AbsenceTypesUID

```