我如何获得昨天的日期,如果当前日期是星期一,我需要星期日,星期六和星期五。已经询问here ms访问。我现在需要这个用于SQL服务器。我该怎么做呢?
将创建一个将在SQL中返回上一个日期的内联视图它将返回1到3行,具体取决于当前日期。
如果当前日期是星期一返回:
Sundays date
Saturdays date
Fridays date
我希望这有助于解释我想要做的更清楚。
样本选择查询
--get previous date
select * from [Purchase Orders] where MyDate in (previous date(s))
答案 0 :(得分:0)
虽然不完全清楚这个问题。但你可以在类似的路线上做点什么
使用DATEPART
和DATEADD
DECLARE @TodaysDate DATETIME
SET @TodaysDate = '2013-04-10'
SELECT CASE
WHEN DATEPART (DW, DATEADD (DD, -1, @TodaysDate )) IN (1, 6, 7)
THEN 'WeekEnd' ELSE 'WeekDay'
END D
答案 1 :(得分:0)
使用您链接的查询,您可以尝试以下代码:
SELECT *
FROM [Purchase Order]
WHERE MyDate >= CASE
WHEN DATENAME(dw, CONVERT(CHAR(8), GETDATE() , 112)) LIKE 'Monday' THEN CONVERT(CHAR(8), DATEADD(dd, -3, GETDATE()), 112)
ELSE CONVERT(CHAR(8), DATEADD(dd, -1, GETDATE()), 112)
END
AND MyDate < CONVERT(CHAR(8),GETDATE(),112)
答案 2 :(得分:0)
您可以使用以下表格功能:
CREATE FUNCTION dbo.ufnPreviousDay (@suppliedDate DATE)
RETURNS @PreviousDates TABLE (PreviousDate DATE)
AS
BEGIN
INSERT INTO @PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -1, @suppliedDate)
IF DATEPART(WEEKDAY, DATEADD(DAY, @@DATEFIRST - 1, @suppliedDate)) = 1 -- If Monday
BEGIN
INSERT INTO @PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -2, @suppliedDate)
UNION ALL
SELECT
PreviousDate = DATEADD(DAY, -3, @suppliedDate)
END
RETURN
END
你可以像这样使用它:
SELECT
T.*
FROM
dbo.ufnPreviousDay('2018-03-19') AS T
/*
Result:
2018-03-18
2018-03-17
2018-03-16
*/
如果你想要今天的日期:
SELECT
T.*
FROM
YourTable AS T
INNER JOIN dbo.ufnPreviousDay(GETDATE()) AS M ON T.MyDate = M.PreviousDate