我得到了一些每周3年的数据,并编写了提取最后104个星期数据的代码(数据一直持续到2014年12月26日,所以我选择了2013年1月2日的所有数据)。
您知道我如何修改代码(如下所示),以便无论查询何时运行,它都能获得最后两年的数据值吗?如果数据是下周运行的,并且数据是输入到上周可用的代码,我希望它能得到最后104周的数据,根据上周的数据。
如果您知道,请您修改下面的代码好吗?
我正在使用2014。
select
pz.PriceZoneID,
pz.Name,
CAST (ash.Date as date) as Date,
format(sum (Sales), '#,###') as SalesByZone
from AggregatedSalesHistory as ash
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSid
join PriceZone as pz on pz.PriceZoneID = ash.PriceZoneID
WHERE ash.date >= '2013-01-02' and ash.date<= '2014-12-24'
group by pz.PriceZoneID,
pz.Name,
ash.Date
order by PriceZoneID,
ash.Date发布于 2018-08-09 09:28:51
取决于你如何定义两年,但是的,只是改变的地方,到目前为止的2年,喜欢;
WHERE ash.date >= dateadd(year, -2, getdate()) and ash.date <= getdate()如果你想要整整两年,从年初算起,它会更像;
WHERE ash.date >= DATEADD(yy, DATEDIFF(yy, 0, DATEADD(YEAR, -2, GETDATE())), 0) and ash.date <= DATEADD(yy, DATEDIFF(yy, 0, DATEADD(YEAR, -1 ,GETDATE())) + 1, -1)发布于 2018-08-09 09:31:40
请参阅此修改:如果您将日期声明为DECLARE @DATE DATE= '2013-01-02',则只需从@date中抽出2年时间来获取最后2年的数据。
WHERE
ash.date BETWEEN dateadd(year, -2, @DATE) and @DATE如果你想要根据你的要求(
我想要它得到最后104周的数据,基于上周
)。
你可以:
WHERE
ash.date BETWEEN dateadd(WEEK, -104, @DATE) and @DATE请参阅下面的完整代码
DECLARE @DATE DATE= '2013-01-02'
select
pz.PriceZoneID,
pz.Name,
CAST (ash.Date as date) as Date,
format(sum (Sales), '#,###') as SalesByZone
from AggregatedSalesHistory as ash
join v_EnterpriseStructure as es on es.ProductSID = ash.ProductSid
join PriceZone as pz on pz.PriceZoneID = ash.PriceZoneID
WHERE
ash.date BETWEEN dateadd(year, -2, @DATE) and @DATE
group by pz.PriceZoneID,
pz.Name,
ash.Date
order by PriceZoneID,
ash.Datehttps://stackoverflow.com/questions/51763310
复制相似问题