日期:2014-05-18 浏览次数:20682 次
declare @b table(意见 varchar(20),日期 smalldatetime,状态 int)
insert @b select 'asdf','2007-10-11 0:15:15',0
union all select 'fdasd','2007-10-11 0:12:15' ,1
union all select 'asasd','2007-10-12 10:15:15' ,3
union all select 'asds', '2007-10-15 03:12:23' ,3
union all select 'asfd', '2007-10-17 04:32:12' ,2
declare @a table(id int identity(0,1),s smalldatetime,e smalldatetime)
declare @s smalldatetime,@e smalldatetime
select @s='2007-10-09',@e='2007-10-20'
insert @a select top 31 null,null from syscolumns
select convert(varchar(10),aa.ss,120) 日期,aa.状态,count(意见) 意见数 from
(
select a.*,b.* from
(select id,dateadd(day,id,@s) SS from @a where dateadd(day,id,@s) <=@e)a
cross join (select 状态=0 union all select 1 union all select 2 union all select 3) b
) aa
left join @b bb
on datediff(day,aa.ss,bb.日期)=0 and aa.状态=bb.状态
group by aa.ss,aa.状态
order by aa.日期 desc,aa.状态
--result
/*
日期 状态 意见数
---------- ------- -----------
2007-10-09 0 0
2007-10-09 1 0
2007-10-09 2 0
2007-10-09 3 0
2007-10-10 0 0
2007-10-10 1 0
2007-10-10 2 0
2007-10-10 3 0
2007-10-11 0 1
2007-10-11 1 1
2007-10-11 2 0
2007-10-11 3 0
2007-10-12 0 0
2007-10-12 1 0
2007-10-12 2 0
2007-10-12 3 1
2007-10-13 0 0
2007-10-13 1 0
2007-10-13 2 0
2007-10-13 3 0
2007-10-14 0 0
2007-10-14 1 0
2007-10-14 2 0
2007-10-14 3 0
2007-10-15 0 0
2007-10-15 1 0
2007-10-15 2 0
2007-10-15 3 1
2007-10-16 0 0
2007-10-16 1 0
2007-10-16 2 0
2007-10-16 3 0
2007-10-17 0 0
2007-10-17 1 0
2007-10-17 2 1
2007-10-17 3 0
2007-10-18 0 0
2007-10-18 1 0
2007-10-18 2 0
2007-10-18 3 0
2007-10-19 0 0
2007-10-19 1 0
2007-10-19 2 0
2007-10-19 3 0
2007-10-20 0 0
2007-10-20 1 0
2007-10-20 2 0
2007-10-20 3 0
(所影响的行数为 12 行)
*/
declare @b table(意见 varchar(20),日期 smalldatetime,状态 int) insert @b select 'asdf','2007-10-11 0:15:15',0 union all select 'fdasd','2007-10-11 0:12:15' ,1 union all select 'asasd','2007-10-12 10:15:15' ,3 union all select 'asds', '2007-10-15 03:12:23' ,3 union all select 'asfd', '2007-10-17 04:32:12' ,2 declare @a table(id int identity(0,1),s smalldatetime,e smalldatetime) declare @s smalldatetime,@e smalldatetime select @s='2007-10-09',@e='2007-10-20' insert @a select top 31 null,null from syscolumns select convert(varchar(10),aa.ss,120) 日期, aa.状态, count(意见) 意见数 , cast(100 * count(意见)/isnull((select sum(1) from @b where datediff(d,日期,aa.ss) = 0 ),1) as varchar)+'%' 占比 from ( select a.*,b.* from (select id,dateadd(day,id,@s) SS from @a where dateadd(day,id,@s)<=@e)a cross join (select 状态=0 union all select 1 union all select 2 union all select 3) b ) aa left join @b bb on datediff(day,aa.ss,bb.日期)=0 and aa.状态=bb.状态 group by aa.ss,aa.状态 order by aa.日期 des