如何从查询中多次评估数据?

时间:2009-05-12 11:00:51

标签: sql sql-server sql-server-2005

CREATE TABLE #Temp (VisitingCount int, [Time] int )
DECLARE @DateNow DATETIME,@i int,@Time int
set @DateNow='00:00'  
set @i=1;  
while(@i<48)  
    begin  
        set @DateNow = DATEADD(minute, 30, @DateNow)
        set @Time = (datepart(hour,@DateNow)*60+datepart(minute,@DateNow))/30 
        insert into #Temp(VisitingCount,[Time]) values(0,@Time )
        set @i=@i+1
    end

select Sum(VisitingCount)as VisitingCount, [Time] from #Temp group by [Time] Union All select count(page) as VisitingCount, (datepart(hour,Date)*60+datepart(minute,Date))/30 as [Time] from scr_SecuristLog where Date between '2009-05-04 10:30' and '2009-05-04 12:30' GROUP BY (datepart(hour,Date)*60+datepart(minute,Date))/30--scr order by 2 asc

此查询会创建此表格但如果您在下面查看“22”则会重复两次。在这种情况下。我应该下降0值。我需要

 VisitingCount ------------时间----------
重复------------------重复-----
重复------------------重复-----
重复------------------重复-----
 526 ----------------------- 21 ----------
0 -------------------------- 22 ----------
0 -------------------------- 22 ----------
0 -------------------------- 23 ----------
825 ------------------------ 23 ----------
重复------------------重复-----
重复------------------重复-----

我需要这张表

 VisitingCount ------------时间----------
重复------------------重复-----
重复------------------重复-----
重复------------------重复-----
 526 ----------------------- 21 ----------
0 -------------------------- 22 ----------
825 ------------------------ 23 ----------
重复------------------重复-----
重复------------------重复-----

1 个答案:

答案 0 :(得分:1)

再创建一个嵌套级别:

select Sum(VisitingCount)as VisitingCount, [Time]
from (
  select Sum(VisitingCount)as VisitingCount, [Time]
    from #Temp group by [Time]
  Union All
    select count(page) as VisitingCount, 
    (datepart(hour,Date)*60+datepart(minute,Date))/30 as [Time]
    from scr_SecuristLog
    where Date between '2009-05-04 10:30' and '2009-05-04 12:30'
    GROUP BY (datepart(hour,Date)*60+datepart(minute,Date))/30--scr
  ) X
group by [Time]
order by 2 asc