我知道这听起来很简单,但我似乎无法理解它。
我有一个临时表,例如Handler,MonthName,MonthNumber和MTD,这是该月的总数。然后我需要对这些数据进行操作,从4月到3月为每个Handler创建一个运行总计。现在,这是我正在努力的一点。并非所有处理程序都会拥有所有月份的数据。
例如。
Handler MonthName MonthNo MTD
Julian Slaughter April 1 10000
Julian Slaughter June 3 12000
Julian Slaughter July 4 10000
Julian Slaughter September 6 12000
Bob Monkhouse April 1 5000
Bob Monkhouse July 4 5000
所以我希望结果看起来像这样
Julian Slaughter April 1 10000
Julian Slaughter May 2 10000
Julian Slaughter June 3 22000
Julian Slaughter July 4 32000
Julian Slaughter August 5 32000
Julian Slaughter September 6 44000
......等到3月份
Bob Monkhouse April 1 5000
Bob Monkhouse May 2 5000
Bob Monkhouse June 3 5000
Bob Monkhouse July 4 10000
......等到3月份
我已尝试将LEFT JOIN
放入Month Names \ Numbers的表格中,并尝试了
OVER(PARTITION ..... ORDER BY ..... RANGE\ROWS)
但是不能错过几个月。
先谢谢,抱歉格式不佳,不知道如何在这里做表格。
编辑 - 这是我的LEFT JOIN尝试
SELECT
Months.MonthNo,
Department,
Executive,
#8.MonthNo,
MTD = SUM([TY MTD Prem]) OVER (PARTITION BY Department, Executive, [Exec Code] ORDER BY #8.MonthNo RANGE UNBOUNDED PRECEDING)
FROM Months
LEFT JOIN #8 ON Months.MonthNo = #8.MonthNo
对于一位执行官,我只获得4行,而不是我需要的12行。无法向您显示数据保护目的的结果。
答案 0 :(得分:1)
DECLARE @start_date date, @end_date date
SELECT @start_date='2012-04-01',@end_date='2013-03-31'
;WITH xo AS
(
SELECT @start_date AS cte_start_date
UNION ALL
SELECT DATEADD(MONTH, 1, cte_start_date)
FROM xo
WHERE DATEADD(MONTH, 1, cte_start_date) <= @end_date
), x as (
select *,row_number() over (order by cte_start_date) monthno
from xo
)
, y as (
select distinct handler from test
)
SELECT y.handler, datename(mm,x.cte_start_date), x.monthno
,(select sum(mtd) from test a where a.handler=y.handler and a.monthno<=x.monthno) mtd
FROM y
cross join x
order by 1,3
参见SQLFiddle上的示例http://sqlfiddle.com/#!3/7d483/15
答案 1 :(得分:0)
抱歉延误。提出的解决方案是一种享受。我不得不在我的巨型查询的其他各个部分中多次使用相同的代码,但效果很好。