按月运行SQL Server 2008的开放帐户总数

时间:2014-12-04 09:16:30

标签: sql sql-server-2008 common-table-expression

我发现大量文章类似于我正在尝试做的事情,但似乎无法将其复制到工作中。 我有一个交易表,如下所示:

AccountNo   Status  DateComplete    DateDue    State
1147331     OPEN    18/02/2011      10/03/2011  R
1146787     OPEN    07/04/2011      05/04/2011  R
16511       OPEN    29/09/2003      29/09/2003  R
22571       OPEN    15/10/2003      15/10/2003  R
2852403     OPEN    10/11/2014      10/11/2014  R
2851890     OPEN    17/11/2014      17/11/2014  R
1147331     CLOSED  24/06/2011      27/06/2011  R
1146787     CLOSED  14/06/2011      14/06/2011  R
2852403     CLOSED  11/08/2015      11/08/2015  F
2851890     CLOSED  18/08/2015      18/08/2015  F

我无权更改任何数据,因此必须使用我拥有的数据。 “状态”列显示状态是已完成还是未决。因此当它是'F'时,它将具有未来的日期到期所以我使用CASE WHEN State = 'F' THEN DateDue WHEN State = 'R' THEN DateComplete END AS Date语句(如果语法不仅仅是一个例子,请原谅我)。 我想要实现的是按月开立账户的总计。我已经找到了按月累积计数的指南,但是无法逐个找到总计。我需要的最终输出是(不是基于上面的数字)

Month   OpenAccounts
Jan-14  1
Feb-14  3
Mar-14  2
Apr-14  5

如果我不清楚,请高兴地回答任何问题。 (删除原文后我不得不重新发布这个问题。)

2 个答案:

答案 0 :(得分:0)

;with CTE as -- Get all dates with month year combo
( select CASE [STATE] WHEN 'F' THEN DateDue 
                      WHEN 'R' THEN DateComplete END AS TransDate         
 from  @Account
 where Status = 'OPEN'  
 )  
select  DATENAME(mm,T1.TransDate) +'-'+
        CAST (YEAR(T1.TransDate) AS VARCHAR(20)) AS Month,
        count(distinct T2.TransDate) as runsum
from CTE as T2
cross join CTE T1  
where 1= case when  DATENAME(mm,T1.TransDate) +'-'+ 
                    CAST (YEAR(T1.TransDate) AS VARCHAR(20)) =
                    DATENAME(mm,T2.TransDate) +'-'+ 
                    CAST (YEAR(T2.TransDate) AS VARCHAR(20)) 
                    and  T2.TransDate <  T1.TransDate  then 1
              when T2.TransDate <=  T1.TransDate then 1
         end
group by DATENAME(mm,T1.TransDate) +'-'+ 
         CAST (YEAR(T1.TransDate) AS VARCHAR(20))
order by runsum asc  

DEMO

答案 1 :(得分:0)

试试这个:

DECLARE @table TABLE
  (
     mon          INT,
     yr           INT,
     cnt          INT,
     runningtotal INT
  )
DECLARE @runningtotal INT 

INSERT INTO @table
            (mon,
             yr,
             cnt)
SELECT Datepart(MONTH, yourcolumn) AS mon,
       Datepart(YEAR, yourcolumn)  AS yr,
       Count(*)                    cnt
FROM   yourtable
GROUP  BY Datepart(MONTH, yourcolumn),Datepart(YEAR, yourcolumn)

UPDATE @table
SET    @runningtotal = @runningtotal + cnt,
       runningtotal = @runningtotal

SELECT mon,
       yr,
       runningtotal
FROM   @table