[英]Find closest date in SQL Server
我有一個表dbo.X
與DateTime
column Y
,可能有數百條記錄。
我的存儲過程有參數@CurrentDate
,我想找出上面表dbo.X
column Y
的日期,該日期小於且最接近@CurrentDate.
怎么找到它?
where子句將匹配日期小於@CurrentDate的所有行,並且由於它們是后續排序的,因此TOP 1將是與當前日期最接近的日期。
SELECT TOP 1 *
FROM x
WHERE x.date < @CurrentDate
ORDER BY x.date DESC
使用DateDiff並按結果顯示該日期與輸入之間的天數或秒數
像這樣的東西
select top 1 rowId, dateCol, datediff(second, @CurrentDate, dateCol) as SecondsBetweenDates
from myTable
where dateCol < @currentDate
order by datediff(second, @CurrentDate, dateCol)
我認為我有更好的解決方案。
我將展示一些圖像來支持和解釋最終的解決方案。
背景在我的解決方案中,我有一個外匯匯率表。 這些代表不同貨幣的市場匯率。 但是,我們的服務提供商在費率Feed方面存在問題,因此某些費率的值為零。 我想用相同貨幣的匯率填補缺失的數據,這些匯率最接近缺失的匯率。 基本上我想得到最接近的非零利率的RateId,然后我將替換。 (這在我的例子中沒有顯示。)
1)因此,開始時我們可以識別丟失的費率信息:
2)接下來讓我們確定不缺少的費率。 查詢顯示未丟失的費率
3)這個查詢是神奇發生的地方。 我在這里做了一個假設,可以刪除但添加它以提高查詢的效率/性能。 第26行的假設是我希望在缺失/零交易的同一天找到替代交易。 神奇的事情發生在第23行:Row_Number函數添加一個從1開始的自動編號,用於缺失和非缺失事務之間的最短時間差。 下一個最接近的交易的rownum為2等。
請注意,在第25行,我必須加入貨幣,以便我不會使貨幣類型不匹配。 那就是我不想用CHF值替換澳元貨幣。 我想要最接近的匹配貨幣。
4)最后,讓我們獲取RowNum為1 的數據最終查詢
查詢完整查詢如下;
; with cte_zero_rates as
(
Select *
from fxrates
where (spot_exp = 0 or spot_exp = 0)
),
cte_non_zero_rates as
(
Select *
from fxrates
where (spot_exp > 0 and spot_exp > 0)
)
,cte_Nearest_Transaction as
(
select z.FXRatesID as Zero_FXRatesID
,z.importDate as Zero_importDate
,z.currency as Zero_Currency
,nz.currency as NonZero_Currency
,nz.FXRatesID as NonZero_FXRatesID
,nz.spot_imp
,nz.importDate as NonZero_importDate
,DATEDIFF(ss, z.importDate, nz.importDate) as TimeDifferece
,ROW_NUMBER() Over(partition by z.FXRatesID order by abs(DATEDIFF(ss, z.importDate, nz.importDate)) asc) as RowNum
from cte_zero_rates z
left join cte_non_zero_rates nz on nz.currency = z.currency
and cast(nz.importDate as date) = cast(z.importDate as date)
--order by z.currency desc, z.importDate desc
)
select n.Zero_FXRatesID
,n.Zero_Currency
,n.Zero_importDate
,n.NonZero_importDate
,DATEDIFF(s, n.NonZero_importDate,n.Zero_importDate) as Delay_In_Seconds
,n.NonZero_Currency
,n.NonZero_FXRatesID
from cte_Nearest_Transaction n
where n.RowNum = 1
and n.NonZero_FXRatesID is not null
order by n.Zero_Currency, n.NonZero_importDate
CREATE PROCEDURE CurrentDate
@CurrentDate DATETIME
AS
BEGIN
Select * from orders
where OrderDate < @CurrentDate
END
GO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.