Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

1
Can't Figure out How to Get Price History to Join to Order History
Post Body

I've got a query that works but I"m convinced is needlessly complicated. I'll try to keep this simple.

I've got an orders table and a product history table. I need to join the order date to the most recent price in the product history table.

public.orders

pk,- -logdate------- -----product_id----- ----qty

1-- -2016-01-01-- ------widget1-------- ----1

2-- -2016-06-01- ------widget1-------- -----1

3-- -2016-11-01- ------widget1-------- -----1

public.product_history

pk- -change_date----- ----product---- ---cost

11- -2016-01-01------- ----widget1--- ----1.00

12- -2016-09-01------- ----widget1--- ----1.25

13- -2016-11-01------- ----widget1--- ----1.50

INTENDED RESULT

orders.logdate, -orders.product, -orders.qty,- -product_history.cost,-- -product_history.pk

2016-01-01----- -----widget1----- -----1------- --1.00

2016-06-01- ------widget1-------- -----1------- --1.00

2016-11-01- ------widget1-------- -----1------- --1.50

Here's my ugly query that works

with good_start as (

select t.logdate,t.part_desc,sum(qty),max(p.id) as max_id

from orders as t

left JOIN product_history as p on p.part_desc = t.desc and p.logdate <= t.logdate

where not exists(

select id from product_history p1

  where p1.part_desc = p.part_desc

   and p1.logdate <= p.logdate

    and p1.logdate > p.logdate

     limit 1
              ) and t.part_desc = 'widget1'  and t.logdate >= '2016-01-01' and t.logdate < '2016-12-01'

group by logdate,part_desc

order by logdate

) select y.*,x.shipping_cost, x.item_description from good_start as y inner join = product_history as x on y.max_id = x.id

Author
Account Strength
100%
Account Age
9 years
Verified Email
Yes
Verified Flair
No
Total Karma
18,964
Link Karma
2,534
Comment Karma
16,336
Profile updated: 5 days ago
Posts updated: 11 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
7 years ago