连续3个月计数

时间:2018-09-05 20:32:08

标签: sql sql-server

我每月两次获得新帐户列表。我的大多数帐户都已通过渠道,或者可以在第三个月末归为不良线索。因此,我正在研究sql查询,当我收到新列表时,它将在每个日期告诉我程序中的帐户数。

这是我一直在使用的工具(是的,我自己加入了table1):

select t.receiveddate, count(*)
from table1 t
join table1 t2 on t2.number = t.number 
and (t2.receiveddate > Dateadd(month , -3, t.received) AND t2.receiveddate<= 
t.receiveddate)
group by t.receiveddate

我希望最终得到的是我收到新业务的日期的列表,其中包含漏斗中有多少个帐户(我不超过3个月前收到的帐户)的计数。该计数也应包括该日期收到的新帐户。

这里是一个示例,假设业务开始于2000年1月1日,则漏斗中没有人进行第一次计数。让我们还假设我每次都获得100个新帐户,只是为了使本示例简单起见。

  receiveddate    Count
   1/1/2000        100
   1/15/2000       200
   2/1/2000        300
   2/15/2000       300
   3/1/2000        300
   3/15/2000       300

2 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出!

我知道您要去哪里,但是我将使用相关的子查询。我已经包含了样本数据,我将其随机化以使其与真实世界相似-您可以使用update table2 set column2 = 'some_string Date: ' || to_char ((SELECT SUBSTR(column2, INSTR(column2, ':') + 1) AS date_value FROM table2), 'HH24:MI:ss MM/DD/YYYY') || ' '; 语句将其全部更改为100以验证查询):

implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

答案 1 :(得分:0)

您的问题尚不完全清楚。我假设您有一个帐户表,并且每个帐户都有接收日期。

-- One record per account, each with a received-date

create table Account ( AccountID int identity(1,1), 
                       ReceivedDate date )

-- Populate with 1000 random received-dates.
-- DateAdd(month,... gives a range of 60 months
-- DateAdd(day,...   forces either 1st or 15th of the month
-- Of course, the query below will work regardless of the
-- distribution of dates

declare @k int
set @k = 0
while @k < 1000
  begin

     insert into Account ( ReceivedDate ) values
     ( DateAdd ( day,   14*cast( 2*rand()as int), 
       DateAdd ( month,    cast(60*rand()as int), '2000-01-01' ) ) )

     set @k = @k + 1
  end

-- Let's see the list of dates
select * from Account

-- T1 is the list of DISTINCT received-dates
-- Other than that this query almost matches your own attempt

select T1.ReceivedDate, count(*) as InFunnel
from 
  (select distinct ReceivedDate from Account) T1, 
  Account T2
where     T2.ReceivedDate > DateAdd ( month, -3, T1.ReceivedDate )
      and T2.ReceivedDate <= T1.ReceivedDate 
group by T1.ReceivedDate
order by T1.ReceivedDate