1
4

2 回答 2

1

SQL将日期四舍五入到一周的开始......

DATEADD(WEEK, DATEDIFF(WEEK, 0, <theDate>), 0)

NOTE: This is NOT affected by your DATEFIRST environment setting.


SQL有条件地将其向下舍入到星期一或星期三......

CASE WHEN DATEPART(DW, <theDate>) IN (3, 4, 5, 6, 7) THEN
  DATEADD(WEEK, DATEDIFF(WEEK, 0, <theDate>), 0)
ELSE
  DATEADD(WEEK, DATEDIFF(WEEK, 0, <theDate>), 0) + 2
END

NOTE : DATEPART() _IS_ affected by your DATEFIRST environment setting.
       This code has assumed SET DATEFIRST 7


然后,您可以将所有记录放入一个序列中。如果是位置 1,则在基准日期上添加两天(星期一 => 星期三),如果是位置 2,则添加 7 天(星期一 => 下星期一),位置 3 则添加 9 天,依此类推。

这简化为(position / 2) * 7 + (position % 2) * 2...

position : (position / 2) * 7 + (position % 2) * 2
--------------------------------------------------
       0 : 0
       1 : 2
       2 : 7
       3 : 9
       4 : 14
       5 : 16
       6 : 21

请注意,如果您的基准日期恰好是星期三,则您需要将所有其他日期视为具有更高的位置...


所以,我会这样做...

SELECT
  term_lookup.TermDate,
  base_lookup.base_date
  + ((term_lookup.term_id + base_lookup.base_id) / 2) * 7
  + ((term_lookup.term_id + base_lookup.base_id) % 2) * 2   AS new_date
FROM
(
  SELECT
    DATEADD(WEEK, DATEDIFF(WEEK, 0, MIN(TermDate)), 0)                  AS base_date,
    CASE WHEN DATEPART(DW, MIN(TermDate)) IN (1, 2) THEN 0 ELSE 1 END   AS base_id
  FROM
    yourTable
)
  AS base_lookup
CROSS JOIN
(
  SELECT
    TermDate,
    DENSE_RANK() OVER (ORDER BY TermDate) - 1   AS term_id
  FROM
    yourTable
  GROUP BY
    TermDate
)
  AS term_lookup

如果这为您提供了正确的结果,请将它们重新加入您的数据以进行更新。

于 2013-07-10T12:33:17.680 回答
0

尝试这个

UPDATE Table1
SET TermDate = DATEADD(DAY, CASE DATEPART(weekday, TermDate ) 
                        WHEN 1 THEN 1
                        WHEN 2 THEN 0
                        WHEN 3 THEN 1
                        WHEN 4 THEN 0
                        WHEN 5 THEN 4
                        WHEN 6 THEN 3
                        WHEN 7 THEN 2
                     END, TermDate )
于 2013-07-10T12:46:33.233 回答