我怎样才能将#Temp加入sql表?

时间:2009-05-11 14:55:51

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

如何使用scr_SecuristLog Time加入(或联合)#Temp。请看[时间]栏


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 Count(Page) as VisitingCount,[Time]      
from     
( SELECT Page,Date,[user],      
        (datepart(hour,Date)*60+datepart(minute,Date))/30 as [Time]        
        FROM scr_SecuristLog      
) scr_SecuristLog      
where      
        Date between '2009-05-04' and '2009-05-05'    

group by [Time]  order by [Time]  asc        
return

2 个答案:

答案 0 :(得分:1)

编辑:将GROUP BY子句添加到内部查询并将表别名添加到SELECT语句

以下是您的联接语法的样子:

CREATE TABLE #Temp (VisitingCount int, [Time] int )
--
--
-- Insert logic here
--
--
select t.VisitingCount, t.[Time]
from #Temp as t
inner join (
    select count(page) as VisitingCount, (datepart(hour,Date)*60+datepart(minute,Date))/10 as [Time]
    from scr_SecuristLog
    where Date between '2009-05-04' and '2009-05-05'
    group by Date
) as s
    on t.VisitingCount = s.VisitingCount
        and t.Time = s.Time

答案 1 :(得分:0)

由于您使用的是SQL 2005,因此您可能希望使用公用表表达式而不是临时表:

DECLARE
    @date_start DATETIME,
    @date_end DATETIME

SET @date_start = '2009-05-04'
SET @date_end = '2009-05-04'

;WITH Times (start_time, end_time) AS
(
    SELECT
        @date_start AS start_time,
        @date_start AS end_time
    UNION ALL
    SELECT
        DATEADD(mi, 30, start_time) AS start_time,
        DATEADD(mi, 30, end_time) AS end_time
    FROM
        Times
    WHERE
        end_time <= DATEADD(dy, 1, @date_end)
)
SELECT
    start_time,
    end_time,
    COUNT(*)
FROM
    Times T
INNER JOIN dbo.scr_SecuristLog SL ON
    SL.date >= T.start_time AND
    SL.date < T.end_time
GROUP BY
    start_time,
    end_time