简体   繁体   English

如何将#Temp与sql表一起加入?

[英]How can i join #Temp with sql table?

How can i join ( or union) #Temp with scr_SecuristLog Time. 我如何使用scr_SecuristLog时间加入(或合并)#Temp。 Look please [Time] column 请看[时间]栏


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

EDIT: Added the GROUP BY Clause to the inner query and added table aliases to the SELECT statement 编辑:将GROUP BY子句添加到内部查询,并将表别名添加到SELECT语句

Here's what your join syntax might look like: 您的联接语法可能如下所示:

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

Since you're using SQL 2005, Instead of the temp table you might want to use a common table expression: 由于您使用的是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM