SQL DATEDIFF 非连续日期
我有一个如下所示的表:
Code Mark Date Notional
Beta 5/1/2008 $1,102,451.00
Beta 5/2/2008 $1,102,451.00
Beta 5/5/2008 $1,102,451.00
Beta 5/6/2008 $1,102,451.00
我需要创建一个表,其中一列中包含所有标记日期,并且在另一列中排序时每个相邻标记日期之间的差异。这是我写的 SQL:
SELECT
Current.[Mark Date],
Prev.[Mark Date],
(DATEDIFF("d", Prev.[Mark Date], Current.[Mark Date])/365)
FROM Notional as Prev, Notional as Current
WHERE (Prev.[Mark Date] = (Current.[Mark Date]-1));
但是,此 SQL 不会在周末 5/5/2008 -> 加入例如 2008 年 5 月 2 日或长周末。我将如何让表在非连续日期上自连接?感谢您的帮助!
I've got a table that looks like this:
Code Mark Date Notional
Beta 5/1/2008 $1,102,451.00
Beta 5/2/2008 $1,102,451.00
Beta 5/5/2008 $1,102,451.00
Beta 5/6/2008 $1,102,451.00
I need to create a table that has all of the Mark Dates in one column and the difference between each adjacent Mark Date when sorted in another column. This is the SQL I've written:
SELECT
Current.[Mark Date],
Prev.[Mark Date],
(DATEDIFF("d", Prev.[Mark Date], Current.[Mark Date])/365)
FROM Notional as Prev, Notional as Current
WHERE (Prev.[Mark Date] = (Current.[Mark Date]-1));
However, this SQL will not join over the weekend 5/5/2008 -> 5/2/2008 for example or on long weekends. How would I go about getting the table to self join over non contiguous dates? Thanks for all the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行此操作的唯一方法是在支持行号的 SQL 中按日期排序的选择上使用 ROW_NUMBER(和 ROW_NUMBER+1),或者使用按日期顺序填充的自动增量键创建临时表。
除了诉诸非连接解决方案(即循环)之外,没有其他方法。
The only way to do this is to use ROW_NUMBER (and ROW_NUMBER+1) on a select ordered by date for an SQL that supports row numbers OR to create a temporary table with an auto increment key which you populate in date order.
There is no other way without resorting to a non-join solution (that is a loop.)
在按日期选择并加入该订单时,您可以尝试使用 ROW_NUMBER。
编辑。完成连接。
您可以做的是将表自身连接到大于该行的日期,然后分组并选择最小值。
像这样的东西
我知道这是 Sql Server 代码,但可以轻松更改为 MS Access。
这应该返回以下内容:
You can try to use ROW_NUMBER when selecting and join on that order by the date.
EDIT. Done with joins.
What you can do is to join the table to itself, on dates bigger than that row, and then group by and select the min.
Something like this
I know this is Sql Server code, but can easily be changed to MS Access.
This should return the folowing: