求周,月,6个月内的各项统计
表格式:
table evaluate {
theCode int自增,
saleID int,--用户ID
elevel char(1),--分 "好 ", "中 ", "差 "三种
Dtime Datetime
}
好的一分,中不得分,差得-1分;
根据 saleID,elevel,Dtime来计算;
实现效果:
1周 一个月内 6个月内
好: 5(假想值) 5 0
中: 0 0 0
差: 0 1 0
统计: 5 4 0
一次性得到所有数据
------解决方案--------------------declare @saleID int
set @saleID=1 --参数
select elevel,sum(case when Dtime> =dateadd(week,-1,getdate()) then 1 else 0 end) as [1周]
,sum(case when Dtime> =dateadd(month,-1,getdate()) then 1 else 0 end) as [1个月内]
,sum(case when Dtime> =dateadd(month,-6,getdate()) then 1 else 0 end) as [6个月内]
from evaluate
where saleID=@saleID
group by elevel
union all
select '统计 ',sum(case when Dtime> =dateadd(week,-1,getdate()) then case elevel when '好 ' then 1 when '差 ' then -1 else 0 end else 0 end) as [1周]
,sum(case when Dtime> =dateadd(month,-1,getdate()) then case elevel when '好 ' then 1 when '差 ' then -1 else 0 end else 0 end) as [1个月内]
,sum(case when Dtime> =dateadd(month,-6,getdate()) then case elevel when '好 ' then 1 when '差 ' then -1 else 0 end else 0 end) as [6个月内]
from evaluate
where saleID=@saleID
------解决方案--------------------1、第一个问题,elevel char(1),--修改一下,改成varchar(4)。
2、create table evaluate (theCode int,saleID int,elevel varchar(4),Dtime Datetime)
insert evaluate
select 1,1, '好 ', '2007-09-01 ' union all
select 2,1, '中 ', '2007-08-11 ' union all
select 3,1, '好 ', '2007-09-01 ' union all
select 4,1, '中 ', '2007-09-01 ' union all
select 5,1, '好 ', '2007-07-01 ' union all
select 6,1, '好 ', '2007-09-5 ' union all
select 7,1, '差 ', '2007-09-01 ' union all
select 8,1, '好 ', '2007-09-4 ' union all
select 9,1, '好 ', '2007-08-01 ' union all
select 10,1, '差 ', '2007-09-01 ' union all
select 11,1, '好 ', '2007-09-01 '
select isnull(elevel, '统计 '),sum(case when Dtime> =dateadd(week,-1,getdate()) then 1 else 0 end) as [1周]
,sum(case when Dtime> =dateadd(month,-1,getdate()) then 1 else 0 end) as [1个月内]
,sum(case when Dtime> =dateadd(month,-6,getdate()) then 1 else 0 end) as [6个月内]
from evaluate
group by elevel
with rollup
drop table evaluate