怎么按照时间段来汇总数据
如何按照时间段来汇总数据
时间格式是这样的 : 20141001
数据是这样的:
date xyf cwf bgyf
20140915 120.00 110.00 130.00
20140930 110.00 70.00 60.00
20141005 70.00 80.00 90.00
20141021 30.00 40.00 50.00
最后要合计每个月收入,而且时间段是上个月21号到这个月20号,上面的数据分为三个段2014-08-21到2014-09-20;2014-09-21到2014-10-20;2014-10-21到2014-11-20
最后显示的结果大概为:
九月收入 120.00 110.00 130.00
十月收入 180.00 150.00 150.00
十一月收入 30.00 40.00 50.00
如果按照每个月是1号到最后一天统计是比较简单的,这样分段统计就不知道怎么写了。
------解决思路----------------------
现在改为通用的,试一下下面的sql
------解决思路----------------------
试试这个。 判断DATE列后2位。如果是大于20,把月份加1,(用dateadd加1 就不会出现13月份的问题了。)
然后在对LEFT(date,4)进行分组。
时间格式是这样的 : 20141001
数据是这样的:
date xyf cwf bgyf
20140915 120.00 110.00 130.00
20140930 110.00 70.00 60.00
20141005 70.00 80.00 90.00
20141021 30.00 40.00 50.00
最后要合计每个月收入,而且时间段是上个月21号到这个月20号,上面的数据分为三个段2014-08-21到2014-09-20;2014-09-21到2014-10-20;2014-10-21到2014-11-20
最后显示的结果大概为:
九月收入 120.00 110.00 130.00
十月收入 180.00 150.00 150.00
十一月收入 30.00 40.00 50.00
如果按照每个月是1号到最后一天统计是比较简单的,这样分段统计就不知道怎么写了。
------解决思路----------------------
现在改为通用的,试一下下面的sql
select ny,SUM(xyf) as xyf,SUM(cwf) as cwf,SUM(bgyf) as bgyf
from (
select *,
case when cast(right([date],2) as int)<=20 then cast(substring([date],3,4)
when cast(right([date],2) as int)>20 and cast(substring([date],5,2) as int)!=12 then cast(substring([date],3,4) as int)+1
else cast(cast(substring([date],3,2)+1 as varchar(2))+'01' as int) end as ny
from tablename ) as a group by ny
------解决思路----------------------
with cte as
(select case when right(DATE,2)>=21 then DATEADD(MONTH,1,date)
else date end as date
,xyf,cwf,bgyf from tablename )
select date,SUM(xyf) as xyf,SUM(cwf)as cwf, SUM(bgyf)as bgyf
from cte
group by LEFT(date,4)
试试这个。 判断DATE列后2位。如果是大于20,把月份加1,(用dateadd加1 就不会出现13月份的问题了。)
然后在对LEFT(date,4)进行分组。