2009-05-05 41 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中(如另一個線程中所示)。

相關問題