Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
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
;
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question