2

我必须根据条件计算两天前的日期。

示例日期 = '2012-09-01' 那么 @date 应该是 '2012-08-30' 但如果 2012-08-31 不是工作日,那么 @date 应该是 '2012-08-29'。

你能帮我解决这个问题吗

4

2 回答 2

1

您的问题虽然显然看起来很简单,但并非如此,因为其中涉及许多测试用例(至少我是这样解释的)。让我先编写查询(我假设您使用的是 Sql Server 2005+)

Declare @tbl_Data Table(Dates Date,WorkDayCount Int)

Insert Into @tbl_Data Select '2012-08-25',1
Insert Into @tbl_Data Select '2012-08-26',1
Insert Into @tbl_Data Select '2012-08-27',1
Insert Into @tbl_Data Select '2012-08-28',1
Insert Into @tbl_Data Select '2012-08-29',1
Insert Into @tbl_Data Select '2012-08-30',1
Insert Into @tbl_Data Select '2012-08-31',0
Insert Into @tbl_Data Select '2012-09-01',1

Declare @InputData Date = '2012-09-01'

;WITH CTE AS
(
    SELECT Sequence = ROW_NUMBER() OVER(ORDER BY Dates DESC),*
    FROM @tbl_Data
    WHERE  Dates < @InputData
)
,CTE2 AS
(
    SELECT 
        Sequence = ROW_NUMBER() OVER(ORDER BY Dates DESC)
        ,Dates 
        ,WorkDayCount
    FROM
    (
        SELECT * FROM CTE WHERE Sequence  = ((SELECT TOP 1 Sequence FROM CTE WHERE WorkDayCount = 1)-1)
        UNION  
        SELECT TOP 2 * FROM CTE WHERE WorkDayCount = 1
    )X
)
SELECT TOP 1
            Date = CASE WHEN  Sequence = 1 AND  WorkDayCount = 0 THEN (SELECT Dates FROM CTE2 WHERE  Sequence = 3)
                    WHEN  Sequence = 1 AND  WorkDayCount = 1 THEN (SELECT Dates FROM CTE2 WHERE  Sequence = 2)
            END 
FROM CTE2

案例1:输入日期为9月1日(2012-09-01),前一个日期的WorkDayCount = 0

结果: 2012-08-29

原因:由于 8 月 31 日的 WorkDayCount = 0,所以工作日为 8 月 29 日

案例 2:输入日期为 9 月 1 日(2012-09-01),8 月 31 日 + 8 月 30 日 WorkCount = 0。

结果: 2012-08-28

案例 3:输入日期为 9 月 1 日(2012-09-01),前一个日期的 WorkDayCount = 1

结果: 2012-08-30

如果任何假设/测试用例不正确,请纠正我。

让我知道你的担忧。

于 2012-09-13T04:10:14.507 回答
0

试试这个:

SELECT MIN(DATE_COL) 
FROM  (
        SELECT  TOP 2  DATE_COL 
        FROM TBL_DATE
        WHERE DATE_COL<='2012-09-01'
        AND WORKDAYCOUNT =1)A
于 2012-09-13T03:26:54.370 回答