SELECT the 10 largest value from a database field
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: SELECT the 10 largest value from a database field

  1. #1
    Join Date
    Nov 2008
    Posts
    15

    SELECT the 10 largest value from a database field

    Hi all,

    Let's say I have a table with a DateTime field, How can i select the 10 of the latest date value from that?
    (I want to get 10 latest date)

    What i know is using MAX to get the latest date, but how to get several date instead of only one latest date?

    Thank you.

  2. #2
    Join Date
    Feb 2005
    Location
    Denmark
    Posts
    742

    Re: SELECT the 10 largest value from a database field

    You should use "group by" to achieve your goal; something similar to this:

    Code:
    SELECT TOP 10 MAX(dateTimeField)
    FROM yourTable
    GROUP BY dateTimeField
    ORDER BY dateTimeField DESC

  3. #3
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,840

    Re: SELECT the 10 largest value from a database field

    Maybe I'm confused...But, why not just use LIMIT?

    Code:
    SELECT dateTimeField FROM table ORDER BY dateTimeField DESC LIMIT 0, 10
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  4. #4
    Join Date
    Feb 2005
    Location
    Denmark
    Posts
    742

    Re: SELECT the 10 largest value from a database field

    Quote Originally Posted by PeejAvery View Post
    Maybe I'm confused...But, why not just use LIMIT?

    Code:
    SELECT dateTimeField FROM table ORDER BY dateTimeField DESC LIMIT 0, 10
    Limit is MySQL specific - but you are right, there is no need to over complicate.


    Code:
    SELECT TOP 10 dateTimeField FROM table ORDER BY dateTimeField DESC
    is enough - no need for MAX or GROUP BY or anything
    I think I got confused by the mention of MAX and automatically resorted to GROUP .

  5. #5
    PeejAvery's Avatar
    PeejAvery is offline Super Moderator Power Poster
    Join Date
    May 2002
    Posts
    10,840

    Re: SELECT the 10 largest value from a database field

    Quote Originally Posted by Alsvha View Post
    Limit is MySQL specific
    Ahhh, I did not know that.
    If the post was helpful...Rate it! Remember to use [code] or [php] tags.

  6. #6
    Join Date
    Nov 2008
    Posts
    15

    Re: SELECT the 10 largest value from a database field

    thanks, i have done it with TOP. :P

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center