下面演示了使用CTE生成日期的表格,並生成使用CTE的總結報告。當銷售代表沒有適用的銷售時,他們將被忽略。
嘗試跳轉報告參數,例如設置@RollingMonths
到1
,以獲得更多娛樂。
-- Sample data.
declare @Sales as Table (rep_id Int, month_yr Date, num_sales Int);
insert into @Sales (rep_id, month_yr, num_sales) values
(1, '01/01/2012', 3),
(1, '05/01/2012', 1),
(1, '11/01/2012', 1),
(2, '02/01/2012', 1),
(2, '05/01/2012', 2);
select * from @Sales;
-- Reporting parameters.
declare @ReportEnd as Date = DateAdd(day, 1 - Day(GetDate()), GetDate()); -- The first of the current month.
declare @ReportMonths as Int = 6; -- Number of months to report.
declare @RollingMonths as Int = 12; -- Number of months in rolling sums.
-- Report.
-- A CTE generates a table of month/year combinations covering the desired reporting time period.
with ReportingIntervals as (
select DateAdd(month, 1 - @ReportMonths, @ReportEnd) as ReportingInterval,
DateAdd(month, 1 - @RollingMonths, DateAdd(month, 1 - @ReportMonths, @ReportEnd)) as FirstRollingMonth
union all
select DateAdd(month, 1, ReportingInterval), DateAdd(month, 1, FirstRollingMonth)
from ReportingIntervals
where ReportingInterval < @ReportEnd)
-- Join the CTE with the sample data and summarize.
select RI.ReportingInterval, S.rep_id, Sum(S.num_sales) as R12_Sum
from ReportingIntervals as RI left outer join
@Sales as S on RI.FirstRollingMonth <= S.month_yr and S.month_yr <= RI.ReportingInterval
group by RI.ReportingInterval, S.rep_id
order by RI.ReportingInterval, S.rep_id
使用CTE或數字表來生成所需日期的範圍,然後左外部連接您的數據。 – HABO 2013-03-21 15:10:03
嘿HABO,我會如何實現這個?我創建了一個指定從1/01/11向前的所有日期的CTE。左外連接是否真的會從CTE返回所有行? – Jeremy 2013-03-21 15:25:04
您希望創建一個CTE,以返回報告範圍內每月的第一個月份,例如,過去的12個月。然後加入你的滾動12個月總結表。需要外部聯接以確保輸出中仍包含沒有活動的報告月份。 – HABO 2013-03-21 16:52:57