SA Developer .NET

Welcome to SA Developer .NET Sign in | Join | Help
in Search

Select Second smallest date

Last post 08-08-2008, 12:47 by riccardospagni. 2 replies.
Sort Posts: Previous Next
  •  08-06-2008, 12:31 13908

    Select Second smallest date

    Good day,

    How does one select the second smallest value in a DateTime column if min(columnName) returns the smallest value?

    Thanx.

  •  08-06-2008, 13:42 13911 in reply to 13908

    Re: Select Second smallest date

    simple,

    select min(ColumnName) from TableName where ColumnName > min(ColumnName)

    That works gr8 if your dates are unique. What happens if you have two smallest dates that are the same?

    in SQL server you should be able to : 

    select max(a.columnname) from (select top 2 ColumnName from TableName order by ColumnName asc) a

    in Mysql 

    select max(a.ColumnName) from (select ColumnName from TableName order by ColumnName asc Limit 2) a

    In plain english... get the two smallest dates. Give me the largest of those two. That method will obviously work for the 3rd smallest, 4th smallest, etc..

    The only downside to that is it would be quite slow to execute... anyone have a faster way?

    Cheers

    Paul 

     

  •  08-08-2008, 12:47 13940 in reply to 13911

    Re: Select Second smallest date

    If you're using SQL 2005 you can take advantage of ROW_NUMBER (note: RANK and DENSE_RANK will put duplicate ranking values for duplicate item values, so don't try use them) as in:

     

    SELECT CustomerID, Name, DateAdded, ROW_NUMBER() OVER(ORDER BY DateAdded DESC) AS DateRank WHERE DateRank = 2

     

    (Note 2: I haven't tested the above, as I'm too lazy. It should work, but your results may vary:-P)


    And so the kief looked and lo, it was kief.
View as RSS news feed in XML
Powered by Community Server (Commercial Edition), by Telligent Systems