postgresql - Build SQL query with JOIN and limits -


help me please build postgresql query. there 2 tables: products(id, title) , prices(id, product_id, price_type, moment, value)

moment - timestamp, can in past or future

assume price_type has 2 option: retail or purchase

but 1 product may has many retail prices different moments.

i need select products actual retail , purchase prices, moment less now.

it's can done

select        products.id,        products.title_translations title,       retail_prices.moment ret_moment,       pur_prices.value purchase,       retail_prices.value retail products  left outer join prices pur_prices on products.id=pur_prices.product_id , pur_prices.price_type='purchase' , pur_prices.moment<current_timestamp left outer join prices retail_prices on products.id=retail_prices.product_id , retail_prices.price_type='retail' , retail_prices.moment<current_timestamp order products.id; 

it works, returns product prices, need last prices(by moment).

just use row_number find last price before current time

with last_prices (     select            products.id,            products.title_translations title,           prices.moment,           prices.value,           prices.price_type,           row_number() on (partition product_id, price_type                               order moment desc) rn     products      left join prices       on products.id = prices.product_id      moment < now()    ) select id, title,         max(case when price_type = 'retail'                 moment            end) retail_moment,        max(case when price_type = 'retail'                 value            end) retail_price,        max(case when price_type = 'purchase'                 moment            end) purchase_moment,        max(case when price_type = 'purchase'                 value            end) purchase_price last_prices      rn = 1 group id, title order id 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -