2011-03-18 68 views

回答

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 

查询服用一个月,一年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*[email protected]*100+1 as char(8)) 
    and thedate < dateadd(m,1,cast(@year*[email protected]*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*[email protected]*100+1 as char(8)):一个月
  • dateadd(m,1,..)的第一天:第一天一个月
+0

不是一些奇怪的原因,获取数据后..让我再尝试一次。 – user239684 2011-03-18 10:34:46

+0

理查德感谢您的查询...我只获得第一周的数据,尽管我在2月3日至16日的表格中有数据。 – user239684 2011-03-18 10:59:33

+0

@user使用您正在使用的查询编辑问题,以及一些不计算在内的示例行。你可以尝试我提供的示例表,并至少检查它是否适用于此 - 然后从那里到您的查询。 – RichardTheKiwi 2011-03-18 11:13:55