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

  • SEARCH
  • Home
  • 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 4098596
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T20:19:22+00:00 2026-05-20T20:19:22+00:00

I’m attempting to write a query that will return The most recent AccountDate with

  • 0

I’m attempting to write a query that will return

  1. The most recent AccountDate with a record of 0 per locationID
  2. Then the second most recent AccountDate per locationID. The record can be either 1 or 0.
  3. If there are two AccountDates with the same date then return the most recent AccountDate based on DateAccountLoaded

How ever my solution doesn’t look very elegant. Has anyone got a better way of achieving this.

Please see below my solution

CREATE TABLE [dbo].[TopTwoKeyed](
ID  INT IDENTITY(1,1) PRIMARY KEY(ID),
[LocationID] [int] NULL,
[AccountDate] [date] NULL,
[Record] [tinyint] NULL,
[DateAccountLoaded] [date] NULL
)

INSERT INTO [dbo].[TopTwoKeyed] (
        [LocationID],
        AccountDate,
        Record,
        DateAccountLoaded 
        )

VALUES(1,'2009-10-31',0,'2011-03-23'),
(1,'2008-10-31',1,'2011-03-23'),
(1,'2008-10-31',0,'2010-03-22'),
(1,'2008-10-31',1,'2009-03-23'),
(1,'2011-10-31',1,'2010-03-22'),
(1,'2009-10-31',0,'2010-03-23'),
(2,'2011-10-31',0,'2010-03-23'),
(2,'2010-10-31',0,'2010-03-23'),
(2,'2010-10-31',1,'2010-03-23'),
(2,'2010-10-31',1,'2009-03-23'),
(3,'2010-10-31',0,'2010-03-23'),
(3,'2009-10-31',0,'2010-03-23'),
(3,'2008-10-31',1,'2010-03-23')




    -- Get the most recent Account Date per locationID which has a record type of 0
    SELECT  f.LocationID
            ,f.AccountDate
            ,f.DateAccountLoaded
    FROM    (
            SELECT  ROW_NUMBER() OVER (PARTITION BY LocationID ORDER BY AccountDate DESC,DateAccountLoaded DESC) AS RowNumber
                    ,LocationID AS LocationID
                    ,AccountDate AS AccountDate
                    ,DateAccountLoaded AS DateAccountLoaded
            FROM    [dbo].[TopTwoKeyed]
            WHERE   Record = 0
            ) f
    WHERE   f.RowNumber = 1

    UNION ALL

    SELECT  ff.LocationID
            ,ff.AccountDate
            ,ff.DateAccountLoaded
    FROM    (
            -- Get the SECOND most recent AccountDate. Can be either Record 0 or 1. 
            SELECT  ROW_NUMBER() OVER (PARTITION BY LocationID ORDER BY AccountDate DESC,DateAccountLoaded DESC) AS RowNumber
                    ,LocationID AS LocationID
                    ,AccountDate AS AccountDate
                    ,DateAccountLoaded 'DateAccountLoaded'
            FROM    [dbo].[TopTwoKeyed] tt
            WHERE   EXISTS 
                    (
                    -- Same query as top of UNION. Get the most recent Account Date per locationID which has a record type of 0
                    SELECT  1
                    FROM    (
                            SELECT  ROW_NUMBER() OVER (PARTITION BY LocationID ORDER BY AccountDate DESC,DateAccountLoaded DESC) AS RowNumber
                                    ,LocationID AS LocationID
                                    ,AccountDate AS AccountDate
                            FROM    [dbo].[TopTwoKeyed]
                            WHERE   Record = 0
                            ) f
                    WHERE   f.RowNumber = 1
                    AND     tt.LocationID = f.LocationID 
                    AND     tt.AccountDate < f.AccountDate 
                    )
            ) ff
    WHERE   ff.RowNumber = 1

-- DROP TABLE [dbo].[TopTwoKeyed]
  • 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-20T20:19:23+00:00Added an answer on May 20, 2026 at 8:19 pm

    You could use a row_number subquery to find the most recent account date. Then you can outer apply to search for the next most recent account date:

    select  MostRecent.LocationID
    ,       MostRecent.AccountDate
    ,       SecondRecent.AccountDate
    from    (
            select  row_number() over (partition by LocationID order by 
                        AccountDate desc, DateAccountLoaded desc) as rn
            ,       *
            from    TopTwoKeyed
            where   Record = 0
            ) MostRecent
    outer apply
            (
            select  top 1 *
            from    TopTwoKeyed
            where   Record in (0,1)
                    and LocationID = MostRecent.LocationID
                    and AccountDate < MostRecent.AccountDate
            order by 
                    AccountDate desc
            ,       DateAccountLoaded desc
            ) SecondRecent
    where   MostRecent.rn = 1
    

    EDIT: To place the rows below eachother, you probably have to use a union. A single row_number can’t work because the second row has different criterium for the Record column.

    ; with  Rec0 as
            (
            select  ROW_NUMBER() over (partition by LocationID 
                        order by AccountDate desc, DateAccountLoaded desc) as rn
            ,       *
            from    TopTwoKeyed
            where   Record = 0
            )
    ,       Rec01 as
            (
            select  ROW_NUMBER() over (partition by LocationID 
                        order by AccountDate desc, DateAccountLoaded desc) as rn
            ,       *
            from    TopTwoKeyed t1
            where   Record in (0,1)
                    and not exists
                    (
                    select  *
                    from    Rec0 t2
                    where   t2.rn = 1
                            and t1.LocationID = t2.LocationID
                            and t2.AccountDate < t1.AccountDate
                    )
            )
    select  *
    from    Rec0
    where   rn = 1
    union all
    select  *
    from    Rec01
    where   rn = 1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I know there's a lot of other questions out there that deal with this
I'm trying to select an H1 element which is the second-child in its group

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.