Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Joining tables on sequential values 1

Status
Not open for further replies.

azzazzello

Technical User
Jan 25, 2005
297
US
Hi,

I have 2 tables. One table is called "data". It's defined as follows

date DATE NOT NULL
total int NOT NULL

It is indexed by date and has, say, 300K records per date, and a total of 45M records with a range of dates from, say ,20090101 to 20110401

second table is called "rate" and is defined as follows

date DATE NOT NULL
rate float (10,4) NOT NULL

It has 3 entries:
19800101,5.0
20100525,4.0
20110225,3.0

This basically defines a range of dates for which a rate is valid

I want to return every row from "data" such I get

data.date,total,total*rate where rate is from a rate.date that is CLOSEST AND LESS THAN that of the data.date

I hope this can be done fairly efficiently despite the fact that the "data" table is huge
 
Code:
SELECT data.date
     , data.total
     , data.total * rate.rate   as balance
  FROM data
INNER
  JOIN rate
    ON rate.date =
       ( SELECT MAX(date)
           FROM rate
          WHERE date < data.date )

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top