日期:2014-05-18 浏览次数:20676 次
--sql 2000 declare @sdate datetime declare @edate datetime set @sdate = '2012-01-01' set @edate = getdate() select t1.* , isnull((select count(1) from 新闻 t2 where t2.BranchID = t1.BranchID and datediff(dd,t1.dt,t2.adddate) = 0),0) 数量 from ( select m.dt , n.BranchID from ( select dateadd(dd,num,@sdate) dt from (select isnull((select count(1) from sysobjects where id<t.id),0) as num from sysobjects t) a where dateadd(dd,num,@sdate)<=@edate ) m , 部门 n ) t1
------解决方案--------------------
/**** 部门 BranchID NAME 新闻 NewsID BranchID title adddate 怎么统计 今年每日 每月, 每个部门的发文数据。。当日 或当月没有发文 等于 0 。。。。 *****/ ---只做统计每日的,每月的通过每日的统计出来 ----创建测试数据部门表 create table #部门 ( BranchID varchar(20), NAME varchar(20) ) ---建立部门数据 insert into #部门(BranchID,NAME) values('01','部门1') insert into #部门(BranchID,NAME) values('02','部门2') insert into #部门(BranchID,NAME) values('03','部门3') insert into #部门(BranchID,NAME) values('04','部门4') insert into #部门(BranchID,NAME) values('05','部门5') ----创建测试数据新闻表 create table #新闻 ( NewsID varchar(20), BranchID varchar(20), title varchar(20), adddate datetime ) --建立新闻数据 insert into #新闻(NewsID,BranchID,title,adddate) values('0001','01','新闻1','2012-01-01 09:00:20.327') insert into #新闻(NewsID,BranchID,title,adddate) values('0002','02','新闻2','2012-01-01 09:00:20.327') insert into #新闻(NewsID,BranchID,title,adddate) values('0003','03','新闻3','2012-01-01 09:00:20.327') insert into #新闻(NewsID,BranchID,title,adddate) values('0004','01','新闻4','2012-01-02 09:00:20.327') insert into #新闻(NewsID,BranchID,title,adddate) values('0005','01','新闻5','2012-01-03 09:00:20.327') insert into #新闻(NewsID,BranchID,title,adddate) values('0006','01','新闻6','2012-01-01 10:00:20.327') --创建时间临时表 create table #datetime (dt datetime) ---开始和结束时间 declare @sdate datetime declare @edate datetime select @sdate = '20120101' select @edate = '20120104' ---定义循环变量 declare @dt_temp datetime select @dt_temp = @sdate ---建立时间临时表数据 while datediff(day,@dt_temp,@edate) >= 0 begin insert into #datetime (dt) values (@dt_temp) set @dt_temp = dateadd(day,1,@dt_temp) end select dt,BranchID,SUM(num) from (select dt,brandch_dt.BranchID,#新闻.NewsID, (case when #新闻.NewsID is null then 0 else 1 end) as num from (select * from #datetime,#部门) brandch_dt left join #新闻 on datediff(day,brandch_dt.dt,#新闻.adddate) = 0 and brandch_dt.BranchID = #新闻.BranchID) bran_news_dt group by dt,BranchID order by BranchID