SQL Server查询以计算给定月份名称中的总周数

时间:2011-03-18 06:09:36

标签: sql-server sql-server-2005 sql-server-2008

我需要创建一个报告,我只需要通过月份(二月)和一年(2011年),并希望sum(total)输出所需的输出...我不知道如何计算总周数< / p>

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

1 个答案:

答案 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,..)
  • 后的第一天