2009-05-05 50 views
0

我需要的SQL查询转换表1到表2在sql中更改表格单元格但如何?

select Count(Page) as VisitingCount,CONVERT(VARCHAR(5),Date, 108) as [Time] from scr_SecuristLog  
where Date between '2009-04-30' and '2009-05-02'  
and [user] in(select USERNAME    
    from scr_CustomerAuthorities where customerID=Convert(varchar,4) and ID=Convert(varchar,43))  
group by CONVERT(VARCHAR(5),Date, 108) order by CONVERT(VARCHAR(5),Date, 108) asc



表1

VisitingCount日期
1 ---------------- --- 15:09
3 ------------------- 15:10
7 ---------------- --- 15:15
1 ------------------- 15:39
2 ------------------- 15:40
3 ------------------- 15:47



我怎样才能改变见下表



此表

表2

VisitingCount Date
11 ------------------- 15:00-15:30
6 -------------- ----- 15:30-16:00

回答

1

使用case语句创建一个类别,然后按该类别进行计数。

有关(过于简化)的示例。

select case when Date < '15:30' then '15:00 - 15:30' 
      when Date < '16:00' then '15:30 - 16:00' 
      else 'After 16:00' end as category 
into #temp1 
from Table1 

select count(*) as VistingCount, category as Date 
from #temp1 
group by category 
+0

您可以在不使用临时表的情况下执行此操作,仅通过在相同的CASE语句上进行分组并执行计数 – 2009-05-05 14:46:27

0

请参见我的文章在这个其他线程 - If statement SQL

您可以使用它定义要斗各占通过边界的表。例如。你会有一个像('15:01','15:30','15:00 - 15:30')这样的绑定定义。然后,您只需将数据表加入此边界表中,并将时间段包含在GROUP BY中(如另一个线程中所示)。

相关问题