日期:2014-05-17 浏览次数:20502 次
;with cte(inserttime,result) as
(
select '2013-09-01',0
union all select '2013-09-01',1
union all select '2013-09-01',2
union all select '2013-09-02',1
union all select '2013-09-02',2
)
select inserttime,result,cast(cast((cast(typecount as decimal)/everyTotalCount)*100 as int) as varchar)+'%' as rate
from
(
select inserttime,result,COUNT(*) as typecount,
everyTotalCount=(select COUNT(*) from cte b where a.inserttime=b.inserttime)
from cte a
group by inserttime,result
)t
/*
inserttime result rate
2013-09-01 0 33%
2013-09-01 1 33%
2013-09-01 2 33%
2013-09-02 1 50%
2013-09-02 2 50%
*/
declare @tb table
(inserttime datetime,result int)
insert @tb
select '2013-09-01',0
union all select '2013-09-01',1
union all select '2013-09-01',2
union all select '2013-09-02',1
union all select '2013-09-02',2
union all select '2013-09-02',2
select
convert(varchar(10),a.inserttime,23) inserttime ,Result, a.count*100/b.count ratio
from
(
select inserttime, Result,
SUM(Case when result=result then 1 end) count
from @tb group by inserttime, Result
) a
join
(
select inserttime,
SUM(Case when result=result then 1 end) count
from @tb group by inserttime) b on a.inserttime=b.inserttime
(6 row(s) affected)
inserttime Result ratio
---------- ----------- -----------
2013-09-01 0 33
2013-09-01 1 33
2013-09-01 2 33
2013-09-02 1 33
2013-09-02 2 66
(5 row(s) affected)
--表中有result,inserttime个字段
--result int类型,有0,1,2等几类值
--inserttime datetime类型,是记录插入时间
--想按天查询 result每一类值占当天总数的百分比
--得到如下结果
--2013-09-01 &nb