如何生成这个SQL查询?

时间:2009-05-12 08:56:51

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

“0”是VisitingCount ---数值Value Datepart,例如:00:00-1:00:30-2:01:00-2:01:30- -3


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), [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_SecuristLog.Date 

我的查询返回表格


0   1
0 2
..(removed repeating)..
0 45
0 46
0 47
825 23
526 21
1064 24
885 22



这是我的梦想表。我需要这个:



0   1
0 2
..(removed repeating)..
0 19
0 20
526 21
885 22
825 23
1064 24
0 25
0 26
..(removed repeating)..
0 46
0 47

1 个答案:

答案 0 :(得分:3)

Order By 2 desc添加到您的选择

  select Sum(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 desc

参见UNION (Transact-SQL)

中的示例A.