Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11661

SQL- Query to fetch the row having a maximum date below a certain date

$
0
0

Sorry I couldn't explain this better in the title. Here is essentially what I need to accomplish:

Entity table: entity_idBenchHistory table: entity_id, bench_id, bench_effective_dateSummary table: entity_id, effective_date

That is the database layout in a nutshell. This query finds each entity's effective_date from the Summary table. It also needs to find the bench_id for that particular date, by looking through the BenchHistory table and finding the maximum bench_effective_date that is less than effective_date where BenchHistory.entity_id = Entity.entity_id.

Here is what I have:

SELECT    Entity.entity_id    Summary.effective_date    BenchHistory.bench_idFROM    EntityJOIN Summary ON Entity.entity_id = Summary.entity_idJOIN BenchHistory ON Entity.entity_id = BenchHistory.entity_id

Pretty simple, the bench part is what I'm having trouble with. How do I select only one BenchHistory.bench_id, that must be the most recent relative to Summary.effective_date?

For clarity, Each entity has many corresponding effective_dates and many corresponding bench_ids, but only one bench_id can be "valid" at a time (the most recent one). I am trying to find each row's "valid"bench_id depending on that row's effective_date. I need to do this by determining which bench_id has a bench_effective_date less than effective_date.

Here is an example of a query that I have, maybe it will be easier to visualize then.

SELECT    Entity.entity_id    BenchHistory.bench_id    Summary.effective_date    BenchHistory.bench_effective_dateFROM    EntityJOIN Summary ON Entity.entity_id = Summary.entity_idJOIN BenchHistory ON Entity.entity_id = BenchHistory.entity_id

This will give output like:

entity_id    bench_id    effective_date    bench_effective_date1            120         1/31/2011         6/30/20031            121         1/31/2011         3/22/20051            122         1/31/2011         11/03/20081            123         1/31/2011         1/21/20111            124         12/30/2010        5/15/20101            125         12/30/2010        10/06/2010

What I want to grab, is just bench_id 123 for 1/31, as it is the most recent bench for entity_id = 1 and bench_id 125 for 12/30, etc. So a result set:

entity_id    bench_id    effective_date    bench_effective_date1            123         1/31/2011         1/21/20111            125         12/30/2010        10/06/2010

Thank you, sorry if this is an easy question but I have been working on it for 6 hours trying all sorts of subqueries, aggregates, GROUP BY, and whatever. I am not that experienced with SQL.

:)


Viewing all articles
Browse latest Browse all 11661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>