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
;
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