Hi I am trying to figure out how to return one row from a table that has the highest value in a column. Before I can do that I have to take a substring of that column and convert it to an INT.
The Main table name is "CalendarPeriod"
Here is an example of the column
FiscalPeriod - 0120
I have to take the two characters from the left, which will be the number I am trying to find the MAX value of
Below is a list of the rows with there column Names. FiscalPeriod is the Column that I need to Substring and Cast to an Int to find the max value.
The result of this query should return return the row with the FiscalPeriod "1220" with the Id being "1134", but it is returning the first one.
Here is the query that I found, but I am having trouble trying to figure out how to convert that back to the NVARCHAR. I though that If I added the regular Fiscal Period inside the inner join I would be able to use that in the Where Clause to get the max value, but I was wrong.
I also am Inner Joining another Table "CalendarPeriodHeader" which has the year which I will also need for a comparison in the where. This might be messing up the query results as well, but I am stumped Below is the query I have so far.
Select Top 1 cp.*
From CalendarPeriod as cp
INNER JOIN
(
Select Top 1 Id, Max(Cast(Substring(FiscalPeriod, 1,2) as Int)) as MAXFiscal, FiscalPeriod
From CalendarPeriod
Group By Id, FiscalPeriod
)cp2
On cp2.Id = cp.Id
Inner Join CalendarPeriodHeader as header on header.Id = cp.HeaderId
Where cp2.FiscalPeriod = cp.FiscalPeriod And header.Year = 2020