I am trying to write an SQL Procedure that will calculate the Last Price paid for a certain Part.DECLARE @ItemId int;SET @ItemId = 1;SELECTSD.PriceFROM SalesOrderHeaders AS SHINNER JOIN SalesOrderDetails AS SDON SH.Id = SD.HeaderIdWHERE (SD.LineItemId = @ItemId)AND (SH.OrderDate = (SELECT    MAX(SH.OrderDate) AS Expr1FROM SalesOrderHeaders AS SHINNER JOIN SalesOrderDetails AS SD    ON SH.Id = SD.HeaderIdWHERE (SD.LineItemId = @ItemId)))This does produce the results I wanted but, I am doing everything twice. Would someone point me in a better direction?
SQL Procedure that will calculate the Last Price paid for a certain Part
sql;sql server;t sql;stored procedure
Considering that your subselect is basically the same as your main select, chances are that this subselect is indeed a bit of overkill. Looking at your logic, what you want to achieve is to get the Price of the SalesOrderDetail linked to the SalesOrderHeader with the most recent OrderDate, so let's use an ORDER BY DESC and select only the first answer.I think this should do the trick:SELECT TOP 1 SD.PriceFROM SalesOrderHeaders AS SHINNER JOIN SalesOrderDetails AS SD    ON SH.Id = SD.HeaderIdWHERE SD.LineItemId = @ItemIdORDER BY SH.OrderDate DESC