如果我们有财政周,如何获得日期

时间:2015-10-16 06:05:18

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

我已将财政周存储在我的表中Nvarchar(Max)

CREATE TABLE sample(
                    id int
                    ,FiscalWeekName NvarChar(MAX)
                   );

INSERT INTO sample VALUES(1,'FY15-W1');

不,我想将此fiscalweekname转换为该周的第一天

例如,查询应该返回

01-01-2014

3 个答案:

答案 0 :(得分:2)

我甚至不知道你如何定义财政周,但这是一个刺:

dateadd(
    week,
    cast(substring(FiscalWeekName, 7, 2) as int) - 1,
    dateadd(year, -1, cast('20' + substring(FiscalWeekName, 3, 2) + '0101' as date))
)

数字年本身将投向1月1日,但可能更安全,不依赖于此,所以我添加了'0101'

编辑:在您澄清之后,我试图调整星期几以便回到星期一(而且我假设您的DATEFIRST设置也是如此。这看起来很乱,所以也许有更清洁的方式。

dateadd(
    day,
    (cast(substring(FiscalWeekName, 7, 2) as int) - 1) * 7
      - case
            when cast(substring(FiscalWeekName, 7, 2) as int) > 1
            then
                datepart(
                    dw,
                    dateadd(
                        year,
                        -1,
                        cast('20' + substring(FiscalWeekName, 3, 2) + '0101' as date)
                    )
                )
            else 0
        end,
    dateadd(year, -1, cast('20' + substring(FiscalWeekName, 3, 2) + '0101' as date))
)

答案 1 :(得分:1)

请试试@ shawnt00

的修正
declare @FiscalWeekName as NvarChar(MAX)
set @FiscalWeekName = 'FY15-W2'

SELECT cast(substring(@FiscalWeekName, charindex('W', @FiscalWeekName) + 1, 2) as int),  dateadd(
    wk,
    cast(substring(@FiscalWeekName, charindex('W', @FiscalWeekName) + 1, 2) as int) 
    ,dateadd(yy, -1, cast('20'+substring(@FiscalWeekName, 3, 2)+'0101' as date))
)

答案 2 :(得分:1)

以下解决方案将根据财政+周,

为您提供第一天/星期几
declare @FiscalWeekName as NvarChar(MAX)
set @FiscalWeekName = 'FY15-W5'

DECLARE @FiscalYear as datetime
set @FiscalYear = dateadd(
    WEEK,
    cast(substring(@FiscalWeekName, charindex('W', @FiscalWeekName) + 1, 2) as int) -1
    ,dateadd(yy, -1, cast('20'+substring(@FiscalWeekName, 3, 2)+'0101 01:01:01.1111111' as date))
)

SELECT DATEADD(dd, -(DATEPART(dw, @FiscalYear)-1), @FiscalYear) as FiscalYear