按天分组然后计算每天的结果

时间:2013-10-27 21:56:38

标签: sql sql-server-2008 group-by

我无法理解这个问题。我正在使用MS SQL 2008,我有一个名为Activity的表,有3个字段:customer(客户的身份),visitDate(他们访问的日期)和customerType(他们是什么类型的cutomer)。这是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

请注意,如果有人在同一天多次访问,那么他们当天只被视为一次访问。

我知道这与分组有关,但我不知道从哪里开始。

3 个答案:

答案 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

答案 1 :(得分: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

答案 2 :(得分: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)