计算所有帐户创建帐户的前30天的交易数量

时间:2015-07-16 00:32:47

标签: sql sql-server

我想计算所有帐户创建帐户后前30天的交易次数。问题不是所有帐户都是同时创建的。

Example: [Acct_createdTable]
 Acct   Created_date
909099  01/02/2015
878787  02/03/2003
676767  09/03/2013 

我无法声明日期时间变量,因为它只能占用一个日期时间。 我不能这样做:

Select acctnumber,min,count(*)
 from transaction_table
 where transactiondate between (
    select Created_date from Acct_createdTable where Acct = 909099)
          and    (
    select Created_date from Acct_createdTable where Acct = 909099)+30

从那以后它只计算一个帐户的交易次数。

我想要的输出是什么。

  Acct  First_30_days_count
909099   23 
878787   190
676767   23

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是基本的GROUP BY查询。

SELECT
    ac.acctnumber,
    COUNT(td.id)
FROM Acct_createdTable ac
LEFT JOIN transactiondate td ON
    td.acct = ac.acctnumber
    AND
    td.transaction_date BETWEEN ac.create_date AND DATEADD(30, DAY, ac.create_date)
GROUP BY
    ac.acctnumber

这应该返回每个帐户的前30天内的交易数量。这当然是伪代码,因为您没有说明您的数据库平台。左连接将确保显示该期间没有交易的帐户。

答案 1 :(得分:1)

另一种解决方案是使用outer apply,如下所示:

select a.acct, o.First_30_days_count
from acct_createdtable a 
outer apply (
    select count(*) First_30_days_count
    from transaction_table 
    where acctnumber = a.acct 
    and transactiondate between a.created_date and dateadd(day, 30, a.created_date) 
 ) o;