1

我很难理解这一点。我正在使用 MS SQL 2008,并且我有一个名为 Activity 的表,其中包含 3 个字段:customer(客户的身份)、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

请注意,如果某人在同一天访问了不止一次,则仅将其计为当天的一次访问。

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

4

3 回答 3

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

于 2013-10-27T22:15:46.983 回答
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
于 2013-10-27T21:59:47.200 回答
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)
于 2013-10-27T22:07:34.860 回答