我已经使用NTILE尝试了一些查询,但它不适用于每年计算四分位数。 SQL查询如下。
select distinct datepart(Week,startingdate) as Week,datepart(year,startingdate) as years,sum(users+isnull(tbl_MobileGoogleAnalyticsData.M_Users,0)) as users
into #googleanalyticsUsers
from tbl_GoogleAnalyticsData
left join tbl_MobileGoogleAnalyticsData on tbl_GoogleAnalyticsData.actualdate=tbl_MobileGoogleAnalyticsData.M_ActualDate
group by datepart(Week,startingdate) ,datepart(year,startingdate)
select distinct Week, years,users from #googleanalyticsUsers order by years asc
select distinct week,NTILE(4) OVER(ORDER BY years DESC) AS Quartile,years
from #googleanalyticsUsers
order by years asc
问题是我有一周的数据,所以我需要每年的第13周(每季度一次)加总,这笔钱每年都会发生。怎么办请帮助我。
答案 0 :(得分:0)
无论1月1日是哪一天,您的季度都是13周整整?在这种情况下(52*7=364
),您的一个宿舍将额外增加1或2(闰年)天。您还将有超过52周的时间。您可以在实际的一天使用NTILE,而不是一周的开始。
在任何情况下,您都可以使用NTILE
和Parition by
以及Order by
订购您的周,并将它们分组到几个季度。
以下是一系列日期
的示例;With SequenceNum as
(
Select ROW_NUMBER() Over (Order By C1.Ordinal_Position) Adder
From INFORMATION_SCHEMA.COLUMNS C1, INFORMATION_SCHEMA.COLUMNS C2
),
DateList as
(
Select DateAdd (D, Adder-1, '1/1/2000') as OneDate
From SequenceNum
Where Adder < (365 *10) /* only get 10 years of data*/
)
Select
OneDate,
DatePart (Year, OneDate) YearNum,
DatePart (Week, OneDate) WeekNum,
NTILE(4) Over (Partition By DatePart (Year, OneDate) Order By DatePart (Week, OneDate)) TileValue
From DateList