日期:2014-05-18  浏览次数:20463 次

一个复杂的查询结果,不知道能否用SQL写出来,谢谢了- 统计每季度的累加值。
表结构里的数据,是安月存放,每个月1条记录,现在要统计,每个季度的数据,就是累加3个月的值,这个sql要怎么写??

id     value   time
1       11         2007.01.01
2       12         2007.02.01
3       13         2007.03.01
..............

就是累加每3个月,value的值。

------解决方案--------------------

declare @t table(id int,sl int,d datetime)

insert @t select 1,200, '2007-01-01 ' union
select 1,100, '2007-02-01 ' union
select 1,200, '2007-03-01 ' union
select 1,300, '2007-04-01 ' union
select 1,200, '2007-05-01 ' union
select 1,600, '2007-06-01 ' union
select 1,200, '2007-07-01 ' union
select 1,400, '2007-08-01 ' union
select 1,200, '2007-09-01 ' union

select 1,900, '2007-10-01 ' union
select 1,200, '2007-11-01 '


select sum(sl) as sumsl, datepart(quarter,d) as jd
from @t
group by datepart(quarter,d)
/*


sumsl jd
----------- -----------
500 1
1100 2
800 3
1100 4
*/
------解决方案--------------------
declare @t table(id int,sl int,d datetime)

insert @t select 1,200, '2007-01-01 ' union
select 1,100, '2007-02-01 ' union
select 1,200, '2007-03-01 ' union
select 1,300, '2007-04-01 ' union
select 1,200, '2007-05-01 ' union
select 1,600, '2007-06-01 ' union
select 1,200, '2007-07-01 ' union
select 1,400, '2007-08-01 ' union
select 1,200, '2007-09-01 ' union

select 1,900, '2007-10-01 ' union
select 1,200, '2007-11-01 '


select sum(sl) as sumsl,DATEDIFF (qq ,DATEADD(yy,DATEDIFF(yy,1,d),0) ,d)
from @t
group by DATEDIFF (qq ,DATEADD(yy,DATEDIFF(yy,1,d),0) ,d)
------解决方案--------------------
create table test(ids int,value int,times datetime)

insert into test values(1,11, '2007.01.01 ')
insert into test values(2,12, '2007.02.01 ')
insert into test values(3,13, '2007.03.01 ')
insert into test values(4,11, '2007.04.01 ')
insert into test values(5,11, '2007.05.01 ')
insert into test values(6,11, '2007.06.01 ')
insert into test values(7,11, '2007.07.01 ')
insert into test values(8,12, '2007.08.01 ')
insert into test values(9,13, '2007.09.01 ')

select sum(value) from test group by DATEPART ( qq, times )

drop table test
------解决方案--------------------
declare @t table(id int,sl int,d datetime)

insert @t select 1,200, '2007-01-01 ' union
select 1,100, '2007-02-01 ' union
select 1,200, '2007-03-01 ' union
select 1,300, '2007-04-01 ' union
select 1,200, '2007-05-01 ' union
select 1,600, '2007-06-01 ' union
select 1,200, '2007-07-01 ' union
select 1,400, '2007-08-01 ' union
select 1,200, '2007-09-01 ' union

select 1,900, '2007-10-01 ' union
select 1,200, '2007-11-01 '

select sum(sl) as sumsl, datepart(quarter,dateadd(mm,-1,d)) as jd
from @t
group by datepart(quarter,dateadd(mm,-1,d)),datepart(yy,dateadd(mm,-1,d))