首页 > 解决方案 > 如何在sql中创建图表以按期间获取客户的帐户数

问题描述

我有一个问题,我们想创建一个请求以按期间添加客户编号。

对于我拥有的每个帐户:accountid、customerid、createddate 和 deleteddate

select accountid,customerid, createddate , deleteddate from account
where customerid = 1

该客户有 4 个帐户:

accountid | customerid | createddate                | deleteddate 

2145      |  6641      | 2018-12-12 10:39:16.457    | 2020-03-26 00:00:12.540

2718      |  6641      | 2020-02-11 15:04:51.643    | 2020-03-26 00:00:04.947

2825      |  46818     | 2020-04-14 15:28:30.400    | 2020-04-29 15:58:30.651
  
2851      |  46818     | 2020-06-05 12:41:45.790    | NULL

所以我想要一张当年的图表来获取客户账户的 nb 不是每个月而是每个修改

例如 02/01/2020 我将有 1 个帐户

03/01/2020 我将拥有 0 个帐户

有可能在 SQL 中做到这一点或类似的事情吗?如果可能的话,我该怎么做。

标签: sqlsql-server

解决方案


不是每个月而是每次修改都获取客户帐户的nb

这是你想要的吗?

select 
    x.customer_id, 
    x.modifdate, 
    sum(x.cnt) over(partition by x.customer_id order by x.modifdate) no_active_accounts
from mytable t
cross apply (
    values (customer_id, createddate, 1), (customer_id, deleteddate, -1)
) as x(customer_id, modifdate, cnt)
where modifdate is not null

对于每个客户,每次创建或删除帐户时都会生成一条记录,其中包含修改日期和活动帐户的运行计数。


推荐阅读