简体   繁体   中英

SQL Join When Dates Codes are Involved

I was curious about something. Let's say I have two tables, one with sales and promo codes, the other with only promo codes and attributes. Promo codes can be turned on and off, but promo attributes can change. Here is the table structure:

tblSales                    tblPromo
sale  promo_cd  date        promo_cd  attribute   active_dt  inactive_dt
  2     AAA    1/1/2013        AAA      "fun"      1/1/2013    1/1/3001
  3     AAA    6/2/2013        BBB      "boo"      1/1/2013    6/1/2013
  8     BBB     2/2/2013       BBB      "green"    6/2/2013    1/1/3001
  9     BBB     2/3/2013
  10    BBB     8/1/2013

Please note, this is not my table/schema/design. I don't understand why they don't just make new promo_cd's for each change in attribute, especially when attribute is what we want to measure. Anyway, I'm trying to make a table that looks like this:

sale  promo_cd   attribute
  2     AAA        fun
  3     AAA        fun
  8     BBB        boo
  9     BBB        boo
  10    BBB        green

The only thing I have done so far is just create an inner join (which causes duplicate records) and then filter by comparing the sale date to the promo active/inactive dates. Is there a better way to do this, though? I was really curious since this is a pretty big set of data and I'd love to keep it efficient.

This is one of those cases where I like to put the filtering conditions right into the JOIN clause. At least in my brain, the duplicate records never make it into the result set. That leaves the WHERE clause for actual filtering conditions.

Select s.sale, s.promo_cd, p.attribute
From tblSales s
  Inner Join tblPromo p 
    on s.promo_cd=p.promo_cd 
    and s.date between p.active_dt and p.inactive_dt

Assuming I understand you correctly, you can use:

SELECT s.sale, s.promo_cd, p.attribute
    FROM tblSales s
    JOIN tblPromo p ON p.promo_cd = s.promo_cd AND s.date BETWEENp.active_dt and p.inactive_dt

This assumes that tblPromo dates will never overlap (which seems likely given the schema they chose)

Just add the date to your JOIN criteria:

SELECT a.sale, a.promo_cd, b.attribute
FROM tblSales a
JOIN tblPromo b
   ON a.promo_cd = b.promo_cd
   AND a.date BETWEEN b.active_dt AND b.inactive_dt

Demo: SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM