通过 TSQL 确定一个月中任意最近的一天?
在我正在处理的每一行数据中,我都有一个日期和一个值:
f1 f2
2012-01-01 00:00:00.000 10
2012-01-10 00:00:00.000 9
2012-02-01 00:00:00.000 19
2012-02-15 00:00:00.000 31
使用 TSQL,我需要返回包含特定年月组合的最新日期的每一行 - 例如,在上面的数据中,我需要返回第二行和第四行,因为 1/10/2012 包含为 2012 年 1 月存储的“最新”日期,而 2/15/2012 是 2012 年 2 月记录的最新日期。期望的结果:
f1 f2
2012-01-10 00:00:00.000 9
2012-02-15 00:00:00.000 31
请注意,这并不像简单地确定“该月的最后一天”或“该月的最后一个工作日”那么简单。
我怀疑我需要使用某种 GROUP BY, HAVING 的组合,其中包括 datepart("day", f1) 上的 MAX,但我不知道如何继续前进。有人可以把我推向正确的方向吗?
In each row of data I'm working with, I have a date, and a value:
f1 f2
2012-01-01 00:00:00.000 10
2012-01-10 00:00:00.000 9
2012-02-01 00:00:00.000 19
2012-02-15 00:00:00.000 31
Using TSQL, I need to return each row which contains the latest DAY for specific year-month combinations - For example, in the data above, I need to return the second and fourth rows since 1/10/2012 carries the "latest" day stored for Jan-2012, and 2/15/2012 is the latest day recorded in Feb-2012. Desired results:
f1 f2
2012-01-10 00:00:00.000 9
2012-02-15 00:00:00.000 31
Note that this isn't as simple as simply determining the "last day of the month" or "last business day of the month".
I suspect I need to use some sort of combination of GROUP BY, HAVING which includes a MAX on datepart("day", f1), but I'm at a loss on how to move forward. Can someone push me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
假设 SQL Server 2005 或更高版本:
Assuming SQL Server 2005 or better: