I have come across an issue which I am not sure how to fix. In my stored procedure I use DATEDIFF() function to return an int for date difference. In my logic I have also subtracted a value from the returned value of DATEDIFF() which is giving me a negative value. This is by design as this logic is for working out rates.
My problem is I am using a case statement but I can't select the column because it is using an Alias. What I aim to do is to write some additional logic where if the value is negative I want it to display as 0.
See my code below for more information:
DATEDIFF(d, vso.pod_ata, ISNULL(cncr.cntr_date3, GETUTCDATE())) - 14 AS dem_days, -- Date difference to work out Demurrage days
DATEDIFF(d, cncr.dc_ata, ISNULL(cncr.empty_return_dt, GETUTCDATE())) - 21 AS det_days,
CASE WHEN dem_days <= 0 THEN 0 END AS 'test1',
CASE WHEN det_days <= 0 THEN 0 END AS 'test2',
Error message is:
Invalid column name 'dem_days'. Invalid column name 'det_days'.
What is the best solution to fix this?