这是指我之前的帖子:Link
系统:Sql Server 2012
使用此脚本,如果CutoffDate的日期是星期六或星期日,我会采用星期五值。
SELECT DISTINCT dbo.ECB.Currency + '-' + CAST(dbo.myTable.CutoffDate AS varchar(30)) AS ComboCurrDate, dbo.ECB.Rate AS ECBrate
FROM dbo.ECB INNER JOIN
dbo.myTable ON dbo.ECB.Date = CASE WHEN datepart(weekday, dbo.myTable.CutoffDate) IN (6, 7) THEN dateadd(d, - ((datepart(weekday,
dbo.myTable.CutoffDate) + 1 + @@DATEFIRST) % 7), dbo.myTable.CutoffDate) ELSE dbo.myTable.CutoffDate END AND
dbo.ECB.Currency = dbo.myTable.InvoiceCurrency
WHERE (dbo.myTable.InvoiceCurrency NOT LIKE 'EUR%')
但现在我需要重写这个以处理假期。或者更好的是,处理ECB表中的不存在的记录。
例如:3月29日星期五,ECB表中没有记录,但myTable.CutoffDate设置为此日期。 有了上面的脚本,我今天没有得到价值。
我现在如何将第28个的ECB值分配给CutoffDate?
一般情况下:如果ECB表中没有一天的记录,那么请尝试ECB表中的上一个日期,依此类推。
希望我能清楚地解释清楚。
感谢您的帮助。
答案 0 :(得分:1)
我认为您应该获取数据中每个截止日期的最新ECB日期。
以下是相关子查询:
SELECT DISTINCT ECB.Currency + '-' + CAST(m.CutoffDate AS varchar(30)) AS ComboCurrDate,
ECB.Rate AS ECBrate
FROM (select m.*,
(select top 1 ecb.date
from ecb
where ecb.currency = m.InvoiceCurrency and ecb.date <= m.CutoffDate
order by ecb.date desc
) as ECBDateToUse
from mytable
) m left outer join
ECB
ON ECB.Date = m.ECBDateToUse and
ECB.Currency = m.InvoiceCurrency
WHERE (m.InvoiceCurrency NOT LIKE 'EUR%')
答案 1 :(得分:0)
我认为您正在寻找LEFT OUTER JOIN
SELECT DISTINCT dbo.ECB.Currency + '-' + CAST(dbo.myTable.CutoffDate AS varchar(30)) AS ComboCurrDate, dbo.ECB.Rate AS ECBrate
FROM mytable LEFT OUTER JOIN ECB ON dbo.ECB.Date = CASE WHEN datepart(weekday, dbo.myTable.CutoffDate) IN (6, 7) THEN dateadd(d, - ((datepart(weekday,
dbo.myTable.CutoffDate) + 1 + @@DATEFIRST) % 7), dbo.myTable.CutoffDate) ELSE dbo.myTable.CutoffDate END AND
dbo.ECB.Currency = dbo.myTable.InvoiceCurrency
无论ECB表中是否有结果,都会从mytable返回所有记录。您可以添加AND ECB.date IS NULL的过滤器,以仅提取ECB表中不存在的记录
答案 2 :(得分:0)
使用外连接,并将所有影响连接外侧的谓词条件置于连接条件中,而不是在where子句中。另外,我可以谦虚地建议你使用表别名和格式来使sql更具可读性。如果读者能够轻松理解您的查询,您将更快地得到问题的答案。
SELECT DISTINCT e.Currency + '-' +
CAST(m.CutoffDate AS varchar(30)) ComboCurrDate,
e.Rate ECBrate
FROM dbo.ECB e Left JOIN dbo.myTable m
ON e.Currency = m.InvoiceCurrency
And m.InvoiceCurrency NOT LIKE 'EUR%'
And e.Date =
CASE WHEN datepart(weekday, m.CutoffDate) IN (6, 7)
THEN dateadd(d, - ((datepart(weekday,
m.CutoffDate) + 1 + @@DATEFIRST) % 7), m.CutoffDate)
ELSE m.CutoffDate END