MSSQL - 过去6周回归过去8周

时间:2015-03-02 09:23:10

标签: sql sql-server dateadd datepart

我遇到周数问题。客户周从星期二开始,因此在星期一结束。所以我做了:

Set DateFirst 2

然后我使用

DateAdd(ww,@WeeksToShow, Date)

偶尔会给我8周的信息。我认为这是因为它过去了一年,但我不知道如何解决它。

如果我这样做:

  (DatePart(dy,Date) / 7) - @WeeksToShow

然后它的效果会更好,但显然不会影响前几年,因为它只是减去数字。

编辑:

我目前的SQL(如果它没有任何数据就有帮助)

Set DateFirst 2

Select 
    DATEPART(yyyy,SessionDate) as YearNo, 
    DATEPART(ww,SessionDate) as WeekNo,
    DATEADD(DAY, 1 - DATEPART(WEEKDAY, SessionDate + SessionTime),     CAST(SessionDate +SessionTime AS DATE)) [WeekStart],
    DATEADD(DAY, 7 - DATEPART(WEEKDAY, SessionDate + SessionTime),     CAST(SessionDate + SessionTime AS DATE)) [WeekEnd],
    DateName(dw,DATEADD(DAY, 7 - DATEPART(WEEKDAY, SessionDate +     SessionTime), CAST(SessionDate + SessionTime AS DATE))) as WeekEndName,
    Case when @ConsolidateSites = 1 then 0 else SiteNo end as SiteNo,
    Case when @ConsolidateSites = 1 then 'All' else CfgSites.Name end as SiteName,
    GroupNo,
    GroupName,
    DeptNo,
    DeptName,
    SDeptNo,
    SDeptName,
    PluNo,
    PluDescription,
    SUM(Qty) as SalesQty,
    SUM(Value) as SalesValue
From 
    PluSalesExtended
Left Join
    CfgSites on PluSalesExtended.SiteNo = CfgSites.No
Where
    Exists (Select Descendant from DescendantSites where Parent in (@SiteNo) and Descendant = PluSalesExtended.SiteNo)
    AND (DATEPART(WW,SessionDate + SessionTime) !=DATEPART(WW,GETDATE()))
    AND SessionDate + SessionTime between DATEADD(ww,@NumberOfWeeks * -1,@StartingDate) and @StartingDate
    AND TermNo = 0
    AND PluEntryType <> 4
Group by
    DATEPART(yyyy,SessionDate),
    DATEPART(ww,SessionDate),
    DATEADD(DAY, 1 - DATEPART(WEEKDAY, SessionDate + SessionTime),     CAST(SessionDate +SessionTime AS DATE)),
    DATEADD(DAY, 7 - DATEPART(WEEKDAY, SessionDate + SessionTime),     CAST(SessionDate + SessionTime AS DATE)),
    Case when @ConsolidateSites = 1 then 0 else SiteNo end,
    Case when @ConsolidateSites = 1 then 'All' else CfgSites.Name end,
    GroupNo,
    GroupName,
    DeptNo,
    DeptName,
    SDeptNo,
    SDeptName,
    PluNo,
    PluDescription

order by WeekEnd

2 个答案:

答案 0 :(得分:2)

这里有两个问题,第一个是我怀疑你将8周的数据定义为DATEPART(WEEK有8个不同的值,在这种情况下你可以通过查看什么来复制问题的根本原因ISO将定义为2015年的第一周:

SET DATEFIRST 2;
SELECT Date, Week = DATEPART(WEEK, Date)
FROM (VALUES 
        ('20141229'), ('20141230'), ('20141231'), ('20150101'),
        ('20150102'), ('20150103'), ('20150104')
    ) d (Date);

给出了:

Date        Week
-----------------
2014-12-29  52
2014-12-30  53
2014-12-31  53
2015-01-01  1
2015-01-02  1
2015-01-03  1
2015-01-04  1

因此,虽然您只有7天,但您有3个不同的周数。问题是DATEPART(WEEK是一个非常简单的函数,并且只返回自一年的第一天起经过的周边界数,更好的函数将是ISO_WEEK,因为这会考虑年份边界很好地:

SET DATEFIRST 2;
SELECT Date, Week = DATEPART(ISO_WEEK, Date)
FROM (VALUES 
        ('20141229'), ('20141230'), ('20141231'), ('20150101'),
        ('20150102'), ('20150103'), ('20150104')
    ) d (Date);

给出了:

Date        Week
-----------------
2014-12-29  1
2014-12-30  1
2014-12-31  1
2015-01-01  1
2015-01-02  1
2015-01-03  1
2015-01-04  1

问题是,这并没有考虑星期二开始的星期,因为ISO周从星期一到星期日运行,你可以稍微调整你的使用量来获得前一天的星期数:

SET DATEFIRST 2;
SELECT Date, Week = DATEPART(ISO_WEEK, DATEADD(DAY, -1, Date))
FROM (VALUES 
        ('20141229'), ('20141230'), ('20141231'), ('20150101'),
        ('20150102'), ('20150103'), ('20150104')
    ) d (Date);

哪会给:

Date        Week
-----------------
2014-12-29  52
2014-12-30  1
2014-12-31  1
2015-01-01  1
2015-01-02  1
2015-01-03  1
2015-01-04  1

因此,12月29日星期一被确认为上一周。问题是内置函数没有ISO_YEAR,因此您需要定义自己的函数。这是一个相当简单的函数,即使如此我几乎从不创建标量函数,因为它们执行得非常糟糕,而是使用内联表值函数,所以为此我会使用:

CREATE FUNCTION dbo.ISOYear (@Date DATETIME)
RETURNS TABLE
AS
RETURN
(   SELECT  IsoYear = DATEPART(YEAR, @Date) + 
                        CASE
                            -- Special cases: Jan 1-3 may belong to the previous year 
                            WHEN (DATEPART(MONTH, @Date) = 1 AND DATEPART(ISO_WEEK, @Date) > 50) THEN -1

                            -- Special case: Dec 29-31 may belong to the next year
                            WHEN (DATEPART(MONTH, @Date) = 12 AND DATEPART(ISO_WEEK, @Date) < 45) THEN 1
                            ELSE 0
                        END
);

只需要使用子查询,但额外的输入在性能方面是值得的:

SET DATEFIRST 2;
SELECT Date, 
    Week = DATEPART(ISO_WEEK, DATEADD(DAY, -1, Date)),
    Year = (SELECT ISOYear FROM dbo.ISOYear(DATEADD(DAY, -1, Date)))
FROM (VALUES 
        ('20141229'), ('20141230'), ('20141231'), ('20150101'),
        ('20150102'), ('20150103'), ('20150104')
    ) d (Date);

或者您可以使用CROSS APPLY

SET DATEFIRST 2;
SELECT Date, 
    Week = DATEPART(ISO_WEEK, DATEADD(DAY, -1, Date)),
    Year = y.ISOYear
FROM (VALUES 
        ('20141229'), ('20141230'), ('20141231'), ('20150101'),
        ('20150102'), ('20150103'), ('20150104')
    ) d (Date)
    CROSS APPLY dbo.ISOYear(d.Date) y;

给出了:

Date        Week    Year
---------------------------
2014-12-29  52      2014
2014-12-30  1       2015
2014-12-31  1       2015
2015-01-01  1       2015
2015-01-02  1       2015
2015-01-03  1       2015
2015-01-04  1       2015

即使使用这种方法,只需在6周前获得一个日期,如果您使用的日期不是星期二,那么您最终将会持续7周,因为您将有5个星期的整周,并且在开始的一个星期这是第二个问题。所以你需要确保你的开始日期是星期二。以下内容将于7周前发布:

SELECT CAST(DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), DATEADD(WEEK, -6, GETDATE())) AS DATE);

this answer中更好地解释了这个逻辑,以下是将在本周开始的部分(基于你的datefirst设置):

SELECT DATEADD(DAY, 1 - DATEPART(WEEKDAY, GETDATE()), GETDATE());

然后我所做的就是用GETDATE()替换第二个DATEADD(WEEK, -6, GETDATE())以便它在6周前获得一周的开始,然后只有一个演员去除时间元素从它。

答案 1 :(得分:0)

这将使您从星期二开始的当前周+前几周开始:

WHERE dateadd(week, datediff(d, 0, getdate()-1)/7 - 4, 1) <= yourdatecolumn

这将显示示例:

DECLARE @wks int = 6 -- Weeks To Show

SELECT 
  dateadd(week, datediff(d, 0, getdate()-1)/7 - 4, 1) tuesday5weeksago,
  dateadd(week, datediff(d, 0, getdate()-1)/7 - 5, 1) tuesday6weeksago,
  dateadd(week, datediff(d, 0, getdate()-1)/7 - 6, 1) tuesday7weeksago,
  dateadd(week, datediff(d, 0, getdate()-1)/7 - @wks + 1, 1) tuesdaydynamicweeksago

结果:

tuesday5weeksago  tuesday6weeksago  tuesday7weeksago  tuesdaydynamicweeksago
2015-01-27        2015-01-20        2015-01-13        2015-01-20