34,590
社区成员
发帖
与我相关
我的任务
分享
DECLARE @date date;
set @date='2013-01-08'
;WITH t1 ( ADate , CDate ) AS (
SELECT '2013-01-01','2013-01-01' union all
SELECT '2013-01-01','2013-01-05' union all
SELECT '2013-01-02','2013-01-03' union all
SELECT '2013-01-02','2013-01-08' union all
SELECT '2013-01-03','2013-01-05' union all
SELECT '2013-01-03','2013-01-04' union all
SELECT '2013-01-05','2013-01-05' union all
SELECT '2013-01-05','2013-01-06' union all
SELECT '2013-01-05', NULL union all
SELECT '2013-01-05','2013-01-05' union all
SELECT '2013-01-06','2013-01-06' union all
SELECT '2013-01-06','2013-01-08' union all
SELECT '2013-01-07', NULL union all
SELECT '2013-01-07', NULL union all
SELECT '2013-01-07','2013-01-07'
)
Select COUNT(*) from t1 where (CDate > @date and ADate <= @date) or (CDate is null and ADate <= @date)
-- ADate 申请日期,CDate 审核日期,null表示还未审核, 算出每天总未审核的数量,算法为当前未审核的数量加上以前未审核的数量之和。
--假如截止日期为2013-01-08 结果为:
/*
申请日期 未审核总数
2013-01-01 1
2013-01-02 3
2013-01-03 4
2013-01-04 3
2013-01-05 3
2013-01-06 3
2013-01-07 5
2013-01-08 3
*/
Declare @date date,@b date ,@e date,@n int,@s int;
set @b='2013-01-01';set @e='2013-07-01'
Declare @t1 table (col date,n int)
set @date = @b
while @date <= @e
begin
;WITH t1 as (Select ApplyDate,RepairDate,OrgID from View_Apply_Base )
Select @n = COUNT(*)+@s from t1 where OrgID='MD' and (RepairDate > @date and ApplyDate <= @date) or (RepairDate is null and ApplyDate <= @date) ;
insert into @t1 (col,n) values (@date,@n);
set @date = DATEADD(day,1,@date)
end
Select * from @t1
--耗时1分58秒
这是个是执行计划 查询一天的时候
[/quote]
@s 没用到,忽略掉吧
Declare @date date,@b date ,@e date,@n int,@s int;
set @b='2013-01-01';set @e='2013-07-01'
Declare @t1 table (col date,n int)
set @date = @b
while @date <= @e
begin
;WITH t1 as (Select ApplyDate,RepairDate,OrgID from View_Apply_Base )
Select @n = COUNT(*)+@s from t1 where OrgID='MD' and (RepairDate > @date and ApplyDate <= @date) or (RepairDate is null and ApplyDate <= @date) ;
insert into @t1 (col,n) values (@date,@n);
set @date = DATEADD(day,1,@date)
end
Select * from @t1
--耗时1分58秒
Declare @date date,@b date ,@e date,@n int;
set @b='2010-07-01';set @e='2013-08-01'
Declare @base table (ADate date,CDate date,OrgID varchar(12))
Insert Into @base (ADate,CDate,OrgAID) Select ApplyDate,RepairDate,OrgID from View_Apply_Base where OrgID='MD' and (RepairDate >= @b or RepairDate is null) and ApplyDate <=@e
Declare @t1 table (col date,n int)
set @date = @b
while @date <= @e
begin
Select @n = COUNT(*) from @base where ((CDate > @date and ADate <= @date) or (CDate is null and ADate <= @date));
insert into @t1 (col,n) values (@date,@n);
set @date = DATEADD(day,1,@date)
end
Select * from @t1
已经解决了。先把数据范围缩小,然后只查一次视图。现在2年耗时6s,已经很满意了