ребят, новый в sql, подскажите как оптимальнее вытащить из одной таблицы последние данные по цене, контракту,
следующий запрос вроде работает, но наверняка можно проще конструкцию написать:
select
names.Medicine,
lastContract.Contract,
lastPrice.Price
from
(select distinct Medicine from dbo.price )as names
left outer join
(select Medicine as Medicine1, Price
from (select row_number() over (partition by Medicine order by DateTime desc) as row#, Medicine, Price, DateTime
from dbo.price where Price != 0) as f1
where f1.row# = 1)
as lastPrice
on names.Medicine = lastPrice.Medicine1
left outer join
(select Medicine as Medicine2, Contract
from (select row_number() over (partition by Medicine order by DateTime desc) as row#, Medicine, Contract, DateTime
from dbo.price where Contract != '') as t2
where t2.row# = 1) as lastContract
on names.Medicine = lastContract.Medicine2