Sql server SQL Server查询以计算给定月份名称中周数的总和
我需要创建一个报告,其中我将通过2011年2月和2月,并希望总产量,但希望像这样的输出。。。我不知道如何计算周总收入Sql server SQL Server查询以计算给定月份名称中周数的总和,sql-server,sql-server-2005,sql-server-2008,Sql Server,Sql Server 2005,Sql Server 2008,我需要创建一个报告,其中我将通过2011年2月和2月,并希望总产量,但希望像这样的输出。。。我不知道如何计算周总收入 Week-1......Week-2......Week-3......Week-4....Total --------------------------------------------------- 工作示例 示例表,只包含Date datetime和amount数字的两列 以月份和年份为参数的查询 declare @month int, @year int sele
Week-1......Week-2......Week-3......Week-4....Total
---------------------------------------------------
工作示例
示例表,只包含Date datetime和amount数字的两列
以月份和年份为参数的查询
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+@月*100+1作为字符8:月的第一天
dateaddm,1,…:月后第一天
Richard感谢您的查询…我只获取了第一周的数据,尽管我的表中有从2月3日到2月16日的数据datewise。@user使用您使用的查询编辑问题,以及一些未统计的示例行。您可以尝试我提供的示例表,并至少检查它是否可以使用该表,然后从那里转到您的查询。
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