Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2008
    Posts
    1

    Unanswered: Sybase Top N in Subquery equivalent

    I know SET ROWCOUNT won't work here, I'm looking for any solution that will let me link my data like I need.

    Two database tables linked in a one-to-many relationship.

    I need to get the data from table 1, and a single field from table 2 based on the earliest date from a date field.

    In SQL it would be easy:

    SELECT Table1.*, (SELECT TOP 1 datefield FROM Table2 WHERE Table2.linkfield = Table1.linkfield ORDER BY datefield) FROM Table1

    I need some way to get the same sort of query in a Sybase database.

    Plan B is importing these two tables into SQL or DB2, and running the queries from there.

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT Table1.*
         , Table2.some_other_colulmn
      FROM Table1
    INNER
      JOIN ( SELECT linkfield
                  , MIN(datefield) AS min_date
               FROM Table2
             GROUP
                 BY linkfield ) AS m
        ON m.linkfield = Table1.linkfield
    INNER
      JOIN Table2
        ON Table2.linkfield = m.linkfield 
       AND Table2.datefield = m.min_date
    notice that the SELECT clause contains "some other field" from Table2

    if it was really the lowest datefield that you wanted, the query would be a lot simpler

    usually, this type of situation wants to have some other column value on the row that has the lowest datefield for each group
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Sep 2012
    Posts
    1

    Smile Thanks a lot!!!

    Hi...
    I was struggling to get equivalent of 'top n' clause in sybase since some hours. n this query helped me

  4. #4
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    you're welcome

    i *heart* search engines

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

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