2009-11-25 146 views

回答

11
SELECT 
DATEADD(day,DATEDIFF(day,'19000107',DATEADD(month,DATEDIFF(MONTH,0,GETDATE() /*YourValuehere*/),30))/7*7,'19000107') 

编辑:正确的,最后,工作从我的同事回答。

0

天哪,这是丑陋的,但这里有云:

DECLARE @dtDate DATETIME 
SET @dtDate = '2009-11-05' 

SELECT DATEADD(dd, -1*(DATEPART(dw, DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, @dtDate)+1, 0)))-1), 
      DateAdd(day, -1, DateAdd(month, DateDiff(month, 0, @dtDate)+1, 0))) 
1
DECLARE @LastDateOfMonth smalldatetime 
SELECT @LastDateOfMonth = DATEADD(month, DATEDIFF(month, -1, GETDATE()), 0) -1 
Select DATEADD(dd,-(CASE WHEN DATEPART(weekday,@LastDateOfMonth) = 1 THEN 0 ELSE DATEPART(weekday,@LastDateOfMonth) - 1 END),@LastDateOfMonth) 
+2

不适用于大多数非美国英语安装... – gbn 2009-11-25 15:00:14

2

的另一种方法,从数据仓库实践借来的。创建一个日期维度表并预加载10年左右。

TABLE dimDate (DateKey, FullDate, Day, Month, Year, DayOfWeek, 
       DayInEpoch, MonthName, LastDayInMonthIndicator, many more..) 

以填补在dimDate最简单的方法是一个下午花与Excel,然后从那里导入到数据库中。一半体面dimDate表有50多列 - 任何你想知道约会的东西。

有了这个地方,问题就变成这样的:

SELECT max(FullDate) 
FROM dimDate 
WHERE DayOfWeek = 'Sunday' 
     AND Month = 11 
     AND Year = 2009; 

从本质上讲,所有日期相关的查询变得更简单。

-1
select next_day(last_day(sysdate)-7, 'Sunday') from dual 
+0

不是原始问题声明的sql 2000 – DasDave 2015-08-17 10:29:05

3
select dateadd(day,1-datepart(dw, getdate()), getdate()) 
2

下周日在SQL,无论哪一天是一周的第一天:返回2011-01-02 23:59:59.000在22日 - 12月2010:

select DateADD(ss, -1, DATEADD(week, DATEDIFF(week, 0, getdate()), 14)) 
1

我找到一些难以理解的解决方案,所以这里是我的带变量的版本来解释步骤。

ALTER FUNCTION dbo.fn_LastSundayInMonth 
(
    @StartDate DATETIME 
,@RequiredDayOfWeek INT /* 1= Sunday */ 
) 
RETURNS DATETIME 
AS 
/* 
A detailed step by step way to get the answer... 

SELECT dbo.fn_LastSundayInMonth(getdate()-31,1) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,2) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,3) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,4) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,5) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,6) 
SELECT dbo.fn_LastSundayInMonth(getdate()-31,7) 
*/ 
BEGIN 
    DECLARE @MonthsSince1900 INTEGER 
    DECLARE @NextMonth INTEGER 
    DECLARE @DaysToSubtract INTEGER 
    DECLARE @FirstDayOfNextMonth DATETIME 
    DECLARE @LastDayOfMonthDayOfWeek INTEGER 
    DECLARE @LastDayOfMonth DATETIME 
    DECLARE @ReturnValue DATETIME 

    SET @MonthsSince1900=DateDiff(month, 0, @StartDate) 
    SET @[email protected]+1 
    SET @FirstDayOfNextMonth = DateAdd(month,@NextMonth, 0) 
    SET @LastDayOfMonth = DateAdd(day, -1, @FirstDayOfNextMonth) 

    SET @ReturnValue = @LastDayOfMonth 

    WHILE DATEPART(dw, @ReturnValue) <> @RequiredDayOfWeek 
     BEGIN 
      SET @ReturnValue = DATEADD(DAY,-1, @ReturnValue) 
     END 

    RETURN @ReturnValue 
END 
相关问题