如上面评论中所述,我可能不了解您的模型 - 所以这是一个简单的入门模型。
现在,如果我想要 2010 日历年的每周销售额
select
CalendarYearWeek
, sum(SalesAmount)
from factSales as f
join dimDate as d on d.DateKey = f.DateKey
where Year = 2010
group by CalendarYearWeek
CalendarYearWeek
是 dimDate 中的一列,varchar(8),例如 '2010-w03',Year
也是 dimDate 中的整数列。
不确定这是否接近您正在寻找的内容,但可能是一个开始。
编辑
dimDate也有这些列:
WeekNumberInEpoch,整数 - 从过去的某个纪元日期开始增加增量。同一周内 dimDate 中的所有行都具有相同的 WeekNumberInEpoch。
DayOfWeek , varchar(10) -- '星期日', '星期一', ...
DayNumberInWeek , 整数 -- 1-7
这使用 CTE,应该适用于最新的 PostgreSQL、SQL Server、Oracle、DB2。对于其他人,您可以将 CTE (q_00) 打包到子查询中。
-- for week to previous week
with
q_00 as (
select
WeekNumberInEpoch
, sum(SalesAmount) as Amount
from factSale as f
join dimDate as d on d.DateKey = f.DateKey
where CalendarYear = 2010
group by WeekNumberInEpoch
)
select
a.WeekNumberInEpoch
, a.Amount as ThisWeekSales
, b.Amount as LastWeekSales
, a.Amount - b.Amount as Difference
from q_00 as a
join q_00 as b on b.WeekNumberInEpoch = a.WeekNumberInEpoch - 1
order by a.WeekNumberInEpoch desc ;
-- for day of week to day of previous week
-- monday to monday, tuesday to tuesday, ...
with
q_00 as (
select
WeekNumberInEpoch
, DayOfWeek
, sum(SalesAmount) as Amount
from factSale as f
join dimDate as d on d.DateKey = f.DateKey
where CalendarYear = 2010
group by WeekNumberInEpoch, DayOfWeek
)
select
a.WeekNumberInEpoch
, a.DayOfWeek
, a.Amount as ThisWeekSales
, b.Amount as LastWeekSales
, a.Amount - b.Amount as Difference
from q_00 as a
join q_00 as b on (b.WeekNumberInEpoch = a.WeekNumberInEpoch - 1
and b.DayOfWeek = a.DayOfWeek)
order by a.WeekNumberInEpoch desc, a.DayOfWeek ;
-- Sliding by day and day difference (= 7)
with
q_00 as (
select
DayNumberInEpoch
, FullDate
, DayOfWeek
, sum(SalesAmount) as Amount
from factSale as f
join dimDate as d on d.DateKey = f.DateKey
where CalendarYear = 2010
group by DayNumberInEpoch, FullDate, DayOfWeek
)
select
a.FullDate as ThisDay
, a.DayOfWeek as ThisDayName
, a.Amount as ThisDaySales
, b.FullDate as PreviousPeriodDay
, b.DayOfWeek as PreviousDayName
, b.Amount as PreviousPeriodDaySales
, a.Amount - b.Amount as Difference
from q_00 as a
join q_00 as b on b.DayNumberInEpoch = a.DayNumberInEpoch - 7
order by a.FullDate desc ;