这应该这样做:
WITH tblProjects2 AS (
SELECT ProjectId, DATEADD(DAY, -Duration, EndDate) AS StartDate FROM tblProjects
)
SELECT ProjectId,
CASE WHEN DATENAME(DW, StartDate) = 'Sunday' THEN DATEADD(day, -2, StartDate)
WHEN DATENAME(DW, StartDate) = 'Saturday' THEN DATEADD(day, -1, StartDate)
ELSE StartDate END AS ProperStartDate
FROM tblProjects2
该方法相当简单 - 当您的新日期在周末时,分别减去 1 或 2 天,具体取决于是周六还是周日。
测试用例结构tblProjects
:
CREATE TABLE [dbo].[tblProjects](
[ProjectId] [int] NULL,
[StartDate] [date] NULL,
[EndDate] [date] NULL,
[Duration] [int] NULL
)
相同的测试用例数据:
INSERT INTO tblProjects VALUES (1, NULL, '10-Jan-2013', 5);
INSERT INTO tblProjects VALUES (2, NULL, '02-FEB-2013', 16);
INSERT INTO tblProjects VALUES (3, NULL, '26-Mar-2013', 50);
编辑- 相同的功能,使用一个函数:
CREATE FUNCTION dbo.getStartDate(@EndDate Date, @Duration int)
RETURNS DATE
AS
BEGIN
DECLARE @newDate DATE;
SET @newDate = DATEADD(day, -@Duration, @EndDate);
RETURN (CASE
WHEN DATENAME(DW, @newDate) = 'Sunday' THEN DATEADD(day, -2, @newDate)
WHEN DATENAME(DW, @newDate) = 'Saturday' THEN DATEADD(day, -1, @newDate)
ELSE @newDate END)
END;
然后你可以像这样重写上面的查询:
SELECT ProjectId, dbo.getStartDate(EndDate, Duration) AS StartDate
FROM tblProjects