I have table like:

```
name    |   timeStamp   |   previousValue   |   newValue    
--------+---------------+-------------------+------------
Mark    |   13.12.2020  |       123         |   155     
Mark    |   12.12.2020  |       123         |    12     
Tom     |   14.12.2020  |       123         |   534     
Mark    |   12.12.2020  |       123         |    31     
Tom     |   11.12.2020  |       123         |    84     
Mark    |   19.12.2020  |       123         |    33     
Mark    |   17.12.2020  |       123         |    96     
John    |   22.12.2020  |       123         |    69     
John    |   19.12.2020  |       123         |    33     

```

I'd like to mix last\_value, count (\*) and group to get this result:

```
name    |   count   |   lastValue   
--------+-----------+-------------
Mark    |       5   |        33
Tom     |       2   |       534
John    |       2   |        69

```

This part:

```
select name, count(*) 
from table 
group by name   

```

returns table:

```
name    |   count   
--------+---------
Mark    |       5   
Tom     |       2   
John    |       2   

```

but I have to add the last value for each name.

How to do it?

Best regards!
['https://Stackoverflow.com/questions/66027931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15133478/']
`LAST_VALUE` is a windowed function, so you'll need to get that value first, and then aggregate:

```sql
WITH CTE AS(
    SELECT [name],
           [timeStamp], --This is a poor choice for a column's name. timestamp is a (deprecated) synonym of rowversion, and a rowversion is not a date and time value
           previousValue,
           newValue,
           LAST_VALUE(newValue) OVER (PARTITION BY [name] ORDER BY [timeStamp] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS lastValue
    FROM dbo.YourTable)
SELECT [Name],
       COUNT(*) AS [count],
       lastValue
FROM CTE
GROUP BY [Name],
         lastValue;

```
I got a solution that works, but here's another one:

```
SELECT 
[name], COUNT([name]), [lastValue]
FROM (
    SELECT 
        [name], FIRST_VALUE([newValue]) OVER (PARTITION BY [name] ORDER BY TimeStamp DESC ROWS UNBOUNDED PRECEDING) AS [lastValue]
        FROM [table] 
    ) xyz GROUP BY [name], [lastValue]

```

Keep well!