【问题标题】:Calculate the number of clients (new and returning) for each year计算每年的客户数量(新客户和回头客)
【发布时间】:2021-02-02 17:09:54
【问题描述】:

大家,

我正在尝试形成一个查询来显示特定年份的客户数量。客户表包含一个字段,client_since,所有客户信息,active_client,date_deleted(当客户取消订阅通信时用作标志)。

每条记录的 client_since 显示他们成为客户的年份 (char(4))。 当我按年份查询时,我得到了新客户的记录,但是,我试图形成查询以向我显示客户的数量(新客户和返回客户)。为了争论,所有的客户都回来了。

假设我在 2008 年有 1 个客户,2009 年有 6 个客户签约,2010 年又有 6 个客户签约,2011 年又有 10 个客户签约,依此类推。我需要查询按年份汇总所有客户。

我做到了:

select count (id) as [New Clients],client_since
from tax_clients 
where client_since >= 2008
group by client_since

结果是:

new clients
1   2009
8   2010
6   2011
6   2012
11  2013
6   2014
9   2015
17  2016
20  2017
13  2018
26  2019
41  2020
7   2021

因此,计算将添加所有新客户端。

谁能给我一些关于如何构建查询的指导?

谢谢

【问题讨论】:

  • 请定义“新”和“返回”?如果客户跳过几年怎么办?样本数据和期望的结果会有所帮助。
  • 新客户是第一次使用该服务,而返回是每年返回的客户。如果客户跳过一年,它将被停用,当它返回时,它将被视为新客户。
  • 您为什么使用不受支持的软件?
  • 这就是我所拥有的。我不做很多数据库的东西,只是基本的。有一天我会升级,但今天,这就是我正在使用的东西..

标签: sql sql-server sql-server-2008 count sum


【解决方案1】:

假设您在客户端活跃时每年有一条记录,那么您可以使用lag():

select client_since, count(*) as num_active_clients,
       sum(case when prev_cs = client_since - 1 then 1 else 0 end) as num_new_clients
from (select t.*,
             lag(client_since) over (partition by id order by client_since) as prev_cs
      from tax_clients t
     ) t
group by client_since

【讨论】:

  • 嗨,戈登。 Lag() 对 sql 2008 无效...不是有效的内置函数。
【解决方案2】:

我正在尝试形成查询以向我显示客户的数量(新客户和回访客户)。为了争论,所有的客户都回来了。

“返回客户”逻辑看起来是一个窗口总和:

select 
    client_since, 
    count(*) as new_clients, 
    sum(count(*)) over(order by client_since) returning_clients
from tax_clients 
where client_since >= 2008
group by client_since
order by client_since

也许非常旧的 SQL Server 版本更喜欢子查询,而不是在同一范围内混合聚合和窗口函数:

select t.*, 
    sum(new_clients) over(order by client_since) returning_clients
from (
    select client_since, count(*) as new_clients
    from tax_clients 
    where client_since >= 2008
    group by client_since
) t
order by client_since

【讨论】:

  • 谢谢。我得到 Msg 102, Level 15, State 1, Line 4 'order' 附近的语法错误。
  • 我没有提到它是 sql 2008...用 over(partition by...) 替换 over(order by...) 得到与 2009 年原始查询相同的结果1 1 2010 8 8 2011 6 6 2012 6 6 2013 11 11 2014 6 6 2015 9 9 2016 17 17 2017 20 20 2018 13 13 2019 26 26 2020 41 41 2021 7 7
  • @Antonio:你需要order by。 partition by 不会做同样的事情。我更新了我的答案,用一个可能在你的旧版本上效果更好的替代方法。
  • lag() 不是一个公认的内置函数,我仍然在最后一个查询 Msg 102, Level 15, State 1, Line 2 'order'附近出现语法错误。
  • GMB,此查询在第 2 行的 order 附近仍然给出语法错误 select t.*, sum(new_clients) over(order by client_since) returned_clients from ( select client_since, count(*) as new_clients from tax_clients t where client_since >= 2008 group by client_since ) order by client_since
猜你喜欢
  • 2021-01-16
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多