简体   繁体   English

找到一周的最后一天

[英]Finding the last day of the week

I have a table with a bunch of dates (option maturity dates to be precise). 我有一个包含一堆日期的表(选项成熟日期准确无误)。 I need to query this database to find the last day of a specific week that is stored in the table. 我需要查询此数据库以查找存储在表中的特定周的最后一天。

All I will be given to query this table is the year, the month and the specific week. 所有我将被要求查询此表是年,月和具体的一周。 And based on this I need to find the date that is stored in the table that matches this. 基于此,我需要找到存储在与此匹配的表中的日期。

I've created the following query to find this specific date March 28 2013 我创建了以下查询以查找此特定日期2013年3月28日

SELECT M_SETNAME, M_LABEL, M_MAT FROM OM_MAT_DBF
WHERE M_SETNAME = 'IMM_OSET  '
AND MONTH(M_MAT) = 3
AND YEAR(M_MAT) = 2013
AND ((DATEPART(day,M_MAT)-1)/7 + 1) = 5

Do you guys have any idea of how I can change the last condition so that March 28th will be considered the 5th week of the month and not the 4th week as it is currently doing. 你们有没有想过如何改变最后一个条件,以便3月28日被认为是本月的第5周,而不是目前正在进行的第4周。

You can also use DATEPART to get the number of the week (in the year), but then, you could also get the 1st of each month, and take the week too so you can have: WEEK OF MY DATE - WEEK OF FIRST DAY FOR THIS MONTH + 1. 您也可以使用DATEPART获取一周的数量(在一年中),但是,您也可以获得每个月的第一个月,并且也可以获得一周,这样您就可以拥有:我的日期 - 第一天的一周这个月+ 1。

Here you have an example... 这里有一个例子......

DECLARE @Dt datetime

SELECT @Dt='03-28-2013'

SELECT DATEPART( wk, @Dt) - DATEPART( wk, Convert(Date,Convert(varchar(4),YEAR(@Dt))
+ '-' + Convert(varchar(2), MONTH(@Dt))
+ '-' + Convert(varchar(2), 1))) + 1

EDIT: Also, looking at your code, you could add the CEILING. 编辑:另外,查看您的代码,您可以添加CEILING。 If the result == 2.7, it means it passed the 2nd week, however, it gets rounded to 2 when it should actually be 3. 如果结果== 2.7,则意味着它通过了第二周,但是当它实际上应该是3时,它会四舍五入为2。

If you add the CEILING and the CONVERT to decimal should work.. 如果你添加CEILING和CONVERT到十进制应该工作..

SELECT  MONTH(@Dt), 
        YEAR(@Dt), 
        ((CEILING(Convert(decimal,DATEPART(day,@Dt)-1)/7)) + 1) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM