我必须根据条件在两天前计算日期。
示例日期='2012-09-01'然后@date应该是'2012-08-30'但是如果2012-08-31不是工作日,那么@date应该是'2012-08-29'。
你能帮我解决这个问题吗?
答案 0 :(得分: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
如果任何假设/测试用例不正确,请更正我。
让我知道你的担忧。
答案 1 :(得分:0)
试试这个:
SELECT MIN(DATE_COL)
FROM (
SELECT TOP 2 DATE_COL
FROM TBL_DATE
WHERE DATE_COL<='2012-09-01'
AND WORKDAYCOUNT =1)A