K
K
kot ok2021-01-21 08:46:08
SQL
kot ok, 2021-01-21 08:46:08

How to get latest entry by latest date?

There is a tb.SO table to which I join two more tables through a left join:
In the tb.Price table, the records for the ID Brewery and Product code fields are repeated, only the price and period ID change (there are 25 million records in this table)
In the tb.Period table, the dates flowing prices
As a result, you need to select products only by the last date (Period ID or Date Period) with a price (Product price)
600914ebe7c19674206321.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-01-21
@rozhnev

Check out the following approach:

SELECT * FROM (
  SELECT
    IDBrewery,
    ProductCode,
    ProductPrice,
    PeriodDate,
    ROW_NUMBER() OVER (PARTITION BY ProductCode ORDER BY PeriodDate DESC) RN
  FROM Price
  JOIN Period ON Period.PeriodID = Price.PeriodID
) LastPrice
WHERE RN = 1
;

MSSQL fiddle here

K
kot ok, 2021-01-21
@kot_tok_ok

My decision:

SELECT 
   q.ID Brewery
  ,q.Product code
  ,q.Product price
  ,q.Date Period
FROM 
  (
    SELECT DISTINCT
        ,s.ID Brewery
        ,s.Product code
        ,MAX (pr.Date Period) OVER (PARTITION BY q.ID Brewery, q.Product code) AS j
    FROM [SO] s
    LEFT JOIN [Price] pr
    ON 		s.ID Brewery = pr.ID Brewery
    AND		s.Product code = pr.Product code

  ) q
LEFT JOIN [Price] pr2
ON 		pr2.ID Brewery = q.ID Brewery
AND		pr2.Product code = q.Product code
AND		pr2.Date Period = q.Date Period

Slava Rozhnev Thank you for your promptness and help)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question