What I am trying to do is to check whether a different table (on a different server) has the data related to exchangerate for the month when the ETA is due.
This is the code:
SELECT distinct
case when month(pod_eta)>month(getdate()) AND month(max(server.database.[dbo].[CustomsExchangeRate].validto))> month(getdate()) then pod_eta
when month(pod_eta)>month(getdate()) AND month(max(server.database.[dbo].[CustomsExchangeRate].validto))= month(getdate()) THEN NULL
ELSE pod_eta end AS ArrDate from staging.dutydata i
The logic on it is that when ETA is next month and we have exchange rate for next month, then use the ETA, if ETA is next month and we have exchange rate for this month, then null, else use pod_eta (if ETA is this month and we have this month's exchange rate)
MSSQL failes as it can't bind server.database.dbo].CustomsExchangeRate].validto.
They have no common keys I can use to join them...
答案 0 :(得分:3)
Just pull it into a variable.
DECLARE @maxMonth int;
SELECT @maxMonth = DATEPART(month,max(validto))
FROM server.database.[dbo].[CustomsExchangeRate];
SELECT distinct
case when month(pod_eta)>month(getdate()) AND @maxMonth > month(getdate()) then pod_eta
when month(pod_eta)>month(getdate()) AND @maxMonth = month(getdate()) THEN NULL
ELSE pod_eta end AS ArrDate
from staging.dutydata i;
Though this seems dangerous to me. What happens when it's December and the max valid to date is the following January?
答案 1 :(得分:-1)
Try this :
SELECT distinct
CASE WHEN month(pod_eta)>month(getdate()) AND month(max(myServer.validto))> month(getdate()) THEN pod_eta
WHEN month(pod_eta)>month(getdate()) AND month(max(myServer.validto))= month(getdate()) THEN NULL
ELSE pod_eta END AS ArrDate
FROM staging.dutydata i, server.database.[dbo].[CustomsExchangeRate] myServer Group by pod_eta