This is a discussion on selecting max and min year within the SQL Server forums, part of the Microsoft SQL Server category; --> I have a table that has a DateTime column which uses a DataTime datatype. How do I retrieve the ...
| |||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| ||||
| I have a table that has a DateTime column which uses a DataTime datatype. How do I retrieve the minimum and maximum year using ms sql? Eugene Anthony *** Sent via Developersdex http://www.developersdex.com *** |
| |||
| On Mar 15, 2:47 pm, Eugene Anthony <solomon_13...@yahoo.com> wrote: > I have a table that has a DateTime column which uses a DataTime > datatype. How do I retrieve the minimum and maximum year using ms sql? > > Eugene Anthony > > *** Sent via Developersdexhttp://www.developersdex.com*** select max(datepart(yy, myColumn)) maxYear, min(datepart(yy, myColumn)) minYear from myTable |
| ||||
| SELECT DATEPART(yy, MAX (foo_date)) AS max_year, DATEPART(yy, MIN (foo_date)) AS min_year FROM Foobar; It is important not to put the DATEPART() inside the aggregate functions. It is easy to find the min and max on a column via indexes or statistics tables. Once you put a funciton inside an aggregate function, you cannot use these tools and have to do a table scan. |