将MonthStart MonthEnd分割为Weeks T-SQL

时间:2015-09-02 23:42:49

标签: sql sql-server sql-server-2008 sql-server-2012

我需要编写一个查询,将下面的MonthStart& MonthEnd日期为4周。以下是截至目前的结果集。如果有人能帮我写这个查询,我真的很感激。我需要查询。

            removeAllActions()
            let anim0 = SKAction.animateWithTextures(frames0,
                timePerFrame: 0.2,
                resize: false,
                restore: true)
            let anim1 = SKAction.animateWithTextures(frames1, timePerFrame: 2.0)
            let seq = SKAction.sequence([anim0, anim1, SKAction.runBlock({self.animateIdle()})])
            self.runAction(seq,withKey:key.rawValue)

我需要将结果设置为这样。

MonthStartDate               MonthEndDate
2015-01-04 00:00:00.000      2015-01-31 00:00:00.000

1 个答案:

答案 0 :(得分:0)

查询

DECLARE @MonthStartDate DATETIME = '2015-01-04 00:00:00.000';              
DECLARE @MonthEndDate   DATETIME = '2015-01-31 00:00:00.000';


WITH X AS 
(
  SELECT TOP (DATEDIFF(DAY,@MonthStartDate,@MonthEndDate) + 1)
         DATEADD(DAY
                ,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1
                ,@MonthStartDate) Dates
  FROM master..spt_values
)
SELECT DISTINCT
       DATEADD(DAY, -(DATEPART(WEEKDAY, Dates)-1), Dates) AS [WeekStart]
      ,DATEADD(DAY, 7-(DATEPART(WEEKDAY, Dates)), Dates)  AS [WeekEnd] 
      ,@MonthStartDate                                    AS [MonthStartDate]
      ,@MonthEndDate                                      AS [MonthEndDate]
FROM X

结果集

╔═════════════════════════╦═════════════════════════╦═════════════════════════╦═════════════════════════╗
║        WeekStart        ║         WeekEnd         ║     MonthStartDate      ║      MonthEndDate       ║
╠═════════════════════════╬═════════════════════════╬═════════════════════════╬═════════════════════════╣
║ 2015-01-04 00:00:00.000 ║ 2015-01-10 00:00:00.000 ║ 2015-01-04 00:00:00.000 ║ 2015-01-31 00:00:00.000 ║
║ 2015-01-11 00:00:00.000 ║ 2015-01-17 00:00:00.000 ║ 2015-01-04 00:00:00.000 ║ 2015-01-31 00:00:00.000 ║
║ 2015-01-18 00:00:00.000 ║ 2015-01-24 00:00:00.000 ║ 2015-01-04 00:00:00.000 ║ 2015-01-31 00:00:00.000 ║
║ 2015-01-25 00:00:00.000 ║ 2015-01-31 00:00:00.000 ║ 2015-01-04 00:00:00.000 ║ 2015-01-31 00:00:00.000 ║
╚═════════════════════════╩═════════════════════════╩═════════════════════════╩═════════════════════════╝