Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4621738
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T02:44:41+00:00 2026-05-22T02:44:41+00:00

In SQL 2005 stored proc I need to run a query that contains a

  • 0

In SQL 2005 stored proc I need to run a query that contains a 1-M. I need to return only 1 of the Many table the one with the earliest date.

I have looked at In SQL how do I write a query to return 1 record from a 1 to many relationship?

and SQL conundrum, how to select latest date for part, but only 1 row per part (unique)

But I am not sure what’s the best solution in my case as I am also doing a Insert Into temp table and using dynamic sorting and paging.

Here is my SQL. What I want is to return many rows of Foo, but only the earliest b.CreatedDate between the start and end data paramaters I pass in where there is normally about 5 rows in Bar for each Foo.

DECLARE      @StartDate datetime 
 DECLARE     @EndDate datetime 

INSERT INTO @Results
          SELECT distinct
                f.Name,
                 f.Price
                b.CreatedDate ,
                // loads more columns removed for brevity   
          FROM
                foo f
            join bar b on f.Id = b.fooId
               // loads more table removed for brevity 
          WHERE
                (@x is null OR f.Id = @x)
            AND (@Deal is null OR f.IsDeal = @Deal)
            AND (@StartDate is null OR sd.SailingDate >= @StartDate)
            AND (@EndDate is null OR sd.SailingDate <= @EndDate)
                  // loads more filters removed for brevity 

        declare @firstResult int, @lastResult int
        set @firstResult = ((@PageNumber-1) * @ItemsPerPage) + 1;
        set @lastResult = @firstResult + @ItemsPerPage;
        select @TotalResults = count(1) from @Results;

        WITH ResultItems AS
        (
            SELECT *, ROW_NUMBER() OVER (
                ORDER BY
                CASE    WHEN @SortBy = 'priceLow' THEN Price END ASC,
                CASE    WHEN @SortBy = 'Soonest' THEN CreatedDate END ASC,
                CASE    WHEN @SortBy = 'priceHigh' THEN Price END DESC
            ) As  RowNumber
            FROM @Results r
        )
        SELECT * from ResultItems
        WHERE RowNumber >= @firstResult AND RowNumber < @lastResult
        ORDER BY
        CASE
            WHEN @SortBy = 'priceHigh' THEN (RANK() OVER (ORDER BY Price desc))
            WHEN @SortBy = 'priceLow' THEN (RANK() OVER (ORDER BY Price))
            WHEN @SortBy = 'Soonest' THEN (RANK() OVER (ORDER BY CreatedDate )) 
        END 

This query as is will return multiple ‘b.CreatedDate’ instead of just the earliest one between my Filters

Update
So I want to See
If my source data is:

Foo
___
1  , Hello
2  , There

Boo
___
1, 1,   2011-2-4
2, 1,   2011-3-6
3, 1,   2012-12-21
4, 2,   2012-11-2

The result would be

1, Hello,2011-2-4
2, There,  2012-11-2
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T02:44:42+00:00Added an answer on May 22, 2026 at 2:44 am

    I think I just got it working by adding a CTE to the top of my query

    ;with cteMinDate as (
        select FooId, min(CreatedDate) As CreatedDate
        from Bar            WHERE
              (@StartDate is null OR CreatedDate>= @StartDate)
              AND (@EndDate is null OR CreatedDate<= @EndDate)
            group by FooId
    )
    

    Same as shown here SQL conundrum, how to select latest date for part, but only 1 row per part (unique). Doing this allows me to remove the date query part from my main query and only do it once in the CTE

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to return Russian text from a SQL Server 2005 database table. In
When I try to run a particular stored procedure on my MS SQL 2005
I have a very long-running stored procedure in SQL Server 2005 that I'm trying
I need to manually migrate modified stored procedures from a DEV SQL Server 2005
I have a SQL Server 2005 stored proc which returns two result sets which
Working in SQL Server 2005, I have a stored procedure that inserts a record
I have a stored procedure in a MS-SQL 2005 database that: Creates two temp
How do you create SQL Server 2005 stored procedure templates in SQL Server 2005
I have a stored procedure in SQL 2005. The Stored Procedure is actually creating
Is there a simple process in SQL 2005 for spitting all of my stored

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.