hmd hmd - 1 year ago 89
SQL Question

Aggregate on datetime in sql with group by

The following are available aggregate functions for SQL

AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

I need to apply aggregate function on datetime field? It is not listed there. Max(), Min() will not work. What I would need is either

  • return the latest date

  • return the earliest date

Is it possible. Can I implement it somehow?

Answer Source

min() and max() work fine with dates

you can also do


select top 1 *
from Table
order by SomeDate desc


select top 1 *
from Table
order by SomeDate 

BTW SQL Server does not have the first() and last() functions

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download