开发者

SQL Server query to calculate total for number of weeks in a given month name

I need to create a report where I will just pass month (February) and year (2011) and want the sum(total) but output desired like this... I don开发者_开发知识库't know how to calculate total weekwise

Week-1......Week-2......Week-3......Week-4....Total 
---------------------------------------------------


Working example

Sample table, contains just 2 columns thedate datetime, amount numeric

select cast(datediff(d, number%1000, getdate()) as datetime) as thedate, number as amount
into testtable
from master..spt_values

The query taking month and year as params

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

Note:

  • cast(@year*10000+@month*100+1 as char(8)) : first day of month
  • dateadd(m,1,..) : first day month after
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜