如何提取财政周日历的第一个日期

时间:2013-08-29 21:39:50

标签: tsql sql-server-2012-express

我在SQL Server 2012 Express中有一个财务日历表。我希望能够拉出每周的第一个日期,并从下周开始连续显示它们。这意味着,我希望第一行显示2013年9月2日,然后是2013年9月9日,2013年9月16日等。以下是我如何构建表以及一些数据。

[dbo].[FiscalCalendar](
    [FiscalDate] [datetime] NULL,
    [FiscalWeekNum] [smallint] NULL,
    [FiscalMonthNum] [smallint] NULL,
    [FiscalMonthName] [varchar](9) NULL,
    [FiscalYear] [smallint] NULL

FiscalDate          FiscalWeekNum   FiscalMonthNum  FiscalMonthName FiscalYear
2013-09-02 00:00:00.000 36          9           September   2013
2013-09-03 00:00:00.000 36          9           September   2013
2013-09-04 00:00:00.000 36          9           September   2013
2013-09-05 00:00:00.000 36          9           September   2013
2013-09-06 00:00:00.000 36          9           September   2013
2013-09-07 00:00:00.000 36          9           September   2013
2013-09-08 00:00:00.000 36          9           September   2013
2013-09-09 00:00:00.000 37          9           September   2013
2013-09-10 00:00:00.000 37          9           September   2013
2013-09-11 00:00:00.000 37          9           September   2013
2013-09-12 00:00:00.000 37          9           September   2013
2013-09-13 00:00:00.000 37          9           September   2013
2013-09-14 00:00:00.000 37          9           September   2013
2013-09-15 00:00:00.000 37          9           September   2013

1 个答案:

答案 0 :(得分:1)

SET DATEFIRST 7;

;WITH x AS 
(
  SELECT <cols>, rn = ROW_NUMBER() OVER 
    (PARTITION BY FiscalWeekNum ORDER BY FiscalDate)
  FROM dbo.FiscalCalendar
  WHERE FiscalDate >= CONVERT(DATE, GETDATE())
    AND DATEPART(WEEKDAY, FiscalDate) = 2
)
SELECT <cols> FROM x WHERE rn = 1;