2013-10-27 55 views
1

我很難解決這個問題。我使用的是MS SQL 2008,我有一個名爲Activity的表格,其中包含3個字段:客戶(客戶的身份),visitDate(他們訪問的日期)和customerType(他們是什麼類型的客戶)。以下是通過3天的數據:按天分組然後統計每天的結果

customer visitDate     customerType 

customer1 2013-10-01 07:00:00.000  A 
customer1 2013-10-01 09:00:00.000  A 
customer2 2013-10-01 10:00:00.000  B 

customer1 2013-10-02 09:00:00.000  A 
customer2 2013-10-02 09:00:00.000  B 
customer3 2013-10-02 09:00:00.000  B 
customer1 2013-10-02 09:00:00.000  A 

customer1 2013-10-03 07:00:00.000  A 

我試圖做到的,是寫一個查詢,數據組顯示的每一天也計算在用戶鍵入的每一天,這樣的結果是這樣的:

visitDate TypeA TypeB Total 

2013-10-01 1  1  2 
2013-10-02 1  2  3 
2013-10-03 1  0  0 

請注意,如果某人在同一天訪問超過一次,那麼他們僅計爲當天的一次訪問。

我知道這與分組有關,但我還沒有弄清楚從哪裏開始。

回答

1

略微有點棘手是隻在指定的日子和類型算一個客戶一次,即使他們有多個記錄這一天的到來:

select 
    visitDate, 
    sum(case when customerType = 'A' then 1 else 0 end) as TypeA, 
    sum(case when customerType = 'B' then 1 else 0 end) as TypeB, 
    count(*) as Total 
from (
    select distinct 
     customer, 
     cast(visitdate as date) as visitdate, 
     customertype from activity 
    ) x 
group by 
    visitdate 

Example SQLFiddle

+0

你是個天才謝謝你。 – Jefferson

0
select visitDate, 
     sum(case when customerType = 'A' then 1 else 0 end) as TypeA, 
     sum(case when customerType = 'B' then 1 else 0 end) as TypeB, 
     count(*) as Total 
from activity 
group by visitDate 
0

這也將削減DateTime場的部分時間:

select 
    cast(visitDate as Date) as visitDate, 
    sum(case customerType when 'A' then 1 else 0 end) as TypeA, 
    sum(case customerType when 'B' then 1 else 0 end) as TypeB, 
    count(*) as Total 
from activity 
group by cast(visitDate as Date)