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 8349237
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T07:56:01+00:00 2026-06-09T07:56:01+00:00

This is simple in theory, but difficult for me to figure out. I have

  • 0

This is simple in theory, but difficult for me to figure out.

I have two SQL Server tables:

  1. List of purchases with purchase date and total

    select total, date from purchases
    
  2. list of miles traveled for a specific job and date of travel

    select travelDate, miles from trips
    

EDIT: To keep the answer/discussion on my question, I am rephrasing the requirement.

I need to figure out the total miles driven between each purchase.

I want more accuracy than an overall average.

I can manually get this by summing all miles from trips in between each purchases date. Now, I just want to automate the process.

The grouping should be such that all trips dates greater than purchases date A and less than purchases date B are part of the purchases date A group.

  • 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-06-09T07:56:03+00:00Added an answer on June 9, 2026 at 7:56 am

    Curing my denseness, I see that your request is quite reasonable by treating the problem as “replacement fuel cost”—thus using the fuel cost of the next fueling rather than the previous cost to buy the fuel actually used (which gets really complicated, really fast). Volume then doesn’t matter. Try this on for size.

    SELECT
       T.*,
       P.*, -- from previous purchase
       N.*, -- from next purchase (NULL if none yet)
       TripCost = N.Total * T.Miles / M.MilesThisFill
    FROM
       dbo.Trips T
       CROSS APPLY (
          SELECT TOP 1 *
          FROM dbo.Purchases P
          WHERE P.[Date] < T.travelDate
          ORDER BY P.[Date] DESC
       ) P
       CROSS APPLY (
          SELECT TOP 1 *
          FROM dbo.Purchases P
          WHERE P.[Date] > T.travelDate
          ORDER BY P.[Date]
       ) N
       CROSS APPLY (
          SELECT Sum(miles) MilesThisFill
          FROM dbo.Trips T2
          WHERE
             T2.[Date] > P.[Date]
             AND T2.[Date] < N.[Date]
       ) M;
    

    Or here’s a version that thinks very differently about the problem but should give the same result. Let me know which one performs better, would ya? (SET STATISTICS IO ON; SET STATISTICS TIME ON;)

    WITH PSeq AS (
       SELECT
          Seq = Row_Number() OVER (ORDER BY [Date]),
          *
       FROM dbo.Purchases
    ), Slices AS (
       SELECT
          FromDate = P.[Date],
          ToDate = N.[Date],
          N.Total
       FROM
          PSeq P
          INNER JOIN PSeq N
             ON P.Seq + 1 = N.Seq
    ), TotalMiles AS (
        SELECT
           S.FromDate,
           Sum(T.Miles) MilesThisFill
        FROM
          Slices S
          INNER JOIN dbo.Trips T
             ON T.travelDate BETWEEN S.FromDate AND S.ToDate
        GROUP BY
           S.FromDate 
    )
    SELECT
       T.travelDate,
       S.FromDate,
       S.ToDate,
       TripCost = S.Total * T.Miles / M.MilesThisFill
    FROM
       Slices S
       INNER JOIN dbo.Trips T
          ON T.travelDate BETWEEN S.FromDate AND S.ToDate 
       INNER JOIN dbo.TotalMiles M
          ON S.FromDate = L.FromDate;
    

    I apologize in advance for any typos or errors… I haven’t tested the code.

    And just for laughs, here’s the first query transmogrified into a version that would work even on SQL Server 2000!

    SELECT
       T.travelDate,
       T.Miles,
       T.ToDate,
       TripCost = P.Total * T.Miles / M.MilesThisFill
    FROM
       (
          SELECT
             T.travelDate,
             T.Miles,
             ToDate = (
                SELECT TOP 1 P.Date
                FROM dbo.Purchases P
                WHERE P.[Date] > T.travelDate
                ORDER BY P.[Date]
             )
          FROM
             dbo.Trips T
       ) T
       INNER JOIN (
          SELECT
             ToDate = (
                SELECT TOP 1 P.Date
                FROM dbo.Purchases P
                WHERE P.[Date] > T2.travelDate
                ORDER BY P.[Date]
             ),
             MilesThisFill = Sum(T2.Miles)
          FROM dbo.Trips T2
          GROUP BY
             (
                SELECT TOP 1 P.Date
                FROM dbo.Purchases P
                WHERE P.[Date] > T2.travelDate
                ORDER BY P.[Date]
             )
       ) M ON T.ToDate = M.ToDate
       INNER JOIN dbo.Purchases P
          ON T.ToDate = P.[Date];
    

    This actually exposes that I might not need to look up the previous purchase date in my first query, if I do it right… so here’s a final version:

    WITH TripData AS (
       SELECT
          T.Miles,
          T.travelDate,
          ToDate = (
             SELECT TOP 1 P.[Date]
             FROM dbo.Purchases P
             WHERE P.[Date] > T.travelDate
             ORDER BY P.[Date]
          )
       FROM
          dbo.Trips T
    )
    SELECT
       T.*,
       P.*,
       TripCost = P.Total * T.Miles / M.MilesThisFill
    FROM
       TripData T
       INNER JOIN dbo.Purchases P
          ON T.ToDate = P.[Date]
       INNER JOIN (
          SELECT
             T2.ToDate,
             Sum(T2.Miles) MilesThisFill
          FROM TripData T2
          GROUP BY
             T2.ToDate
       ) M ON T.ToDate = M.ToDate;
    

    Note: the order of the TripCost expression is important, because Miles and TotalMiles are integers. If you put P.Total last, you will get wrong answers because Miles / TotalMiles will be converted to an integer.

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

Sidebar

Related Questions

This is a very simple task in every language I have ever used, but
OK, this should in theory be simple, but I've tried several things like parent
This is a simple question from algorithms theory. The difference between them is that
consider this simple function def foo(l=[]): if not l: print List is empty else
This will be a bit abstract but I have a method like this: private
I asked this the other day but it was closed, probably because I have
this is more theoretical question. I have written simple chat with my friend. We
Right now I have this implemented in my Dev environment: I store the $SERVER['REMOTE_ADDR']
I always wonder why compilers can't figure out simple things that are obvious to
This simple query session = com.jthink.songlayer.hibernate.HibernateUtil.getSession(); Query q = session.createQuery(recNo from SongChanges); giving this

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.