时间统计查询--(在线等)
现在我一个表里面有两个时间字段,一个是买车时间,一个是车出现问题时间,我要根据这两个时间
做一个统计,一个月内出现问题的有多少?1-3个月的有多少?3-6个月的有多少?6-12个月的有多少?1-3年的有多少?3年以上的有多少?
就是这个时间我不会弄了,因为有闰年和平年啥的,还有每个月有30,31天的,求救!!
[解决办法]
你可以这样,比如说你的表里面的最小的时间是2006-1-1,那么你按照年来统计,比如说2006年到2008,这个是不是就是三年了,那么这样select *,case when year(date) between 2004 and 2006 then '2004年到2006年' when year(date) between 2007 and 2009 then '2007年到2009年' when year(date) between 2010 and 2012 then '2010年到2011年' else '2012年' end as 购车年份 from tbl这样的话你就把年分开了,而且到时候统计,直接按照后面这个购车年份来进行统计
[解决办法]
--姓名 单位 消费 消费时间--a a 12 2012-3-14--b b 32 2012-2-21--a a 42 2012-1-4--b b 6 2012-3-14declare @t table (姓名 varchar(5), 单位 varchar(5), 消费 int,消费时间 varchar(20))insert into @t values('a', 'a' ,12, '2012-3-14')insert into @t values('b', 'b' ,32, '2012-2-21')insert into @t values('a', 'a' ,42, '2012-1-4')insert into @t values('b', 'b', 6 ,'2012-3-14') -- 要求显示的结果集列是这样的--姓名 单位 本日消费 本月消费 本年消费select 姓名,单位,消费时间, (select sum(消费) from @t where 消费时间=GETDATE()and t.单位=单位 group by 姓名,单位)本日消费 , (select sum(消费) from @t where datepart(mm,消费时间)=datepart(mm,GETDATE())and t.单位=单位 group by 姓名,单位)本月消费 , (select sum(消费) from @t where datepart(yy,消费时间)=datepart(yy,GETDATE()) and t.单位=单位 group by 姓名,单位)本年消费 from @t t姓名 单位 消费时间 本日消费 本月消费 本年消费----- ----- -------------------- ----------- ----------- -----------a a 2012-3-14 NULL 12 54b b 2012-2-21 NULL 6 38a a 2012-1-4 NULL 12 54b b 2012-3-14 NULL 6 38(4 行受影响)