我需要创建一个报告,我只需要通过月份(二月)和一年(2011年),并希望sum(total)
输出所需的输出...我不知道如何计算总周数< / p>
Week-1......Week-2......Week-3......Week-4....Total
---------------------------------------------------
答案 0 :(得分:0)
工作示例
示例表,仅包含2列thedate datetime, amount numeric
select cast(datediff(d, number%1000, getdate()) as datetime) as thedate, number as amount
into testtable
from master..spt_values
将月份和年份作为参数的查询
declare @month int, @year int
select @month = 2, @year = 2011
select *
from
(
select
amount,
'Week-' + right(dense_rank() over (order by datepart(wk, thedate)),1) week_in_month
from testtable
where thedate >= cast(@year*10000+@month*100+1 as char(8))
and thedate < dateadd(m,1,cast(@year*10000+@month*100+1 as char(8)))
) P
pivot (sum(amount) for week_in_month in ([Week-1],[Week-2],[Week-3],[Week-4],[Week-5])) V
注意:
cast(@year*10000+@month*100+1 as char(8))
:每月的第一天dateadd(m,1,..)
: