MsSQL:查找在历史范围内丢失的帐户

时间:2014-06-11 17:15:00

标签: sql-server

我有一个包含以下列的数据库:

ReportMonth, AccountID, Status

每月运行一个报告,填写指定月份的AccountID和状态数据。但是,这是一个已知问题,有时报告不会填充帐户的状态(即使它应该是)。

我想设计一个查询来查找这些“已删除”的帐户,并报告他们失踪的所有月份。例如,假设我在2014年1月(以及前几个月)报告了帐户123。现在是2014年6月,我没有任何关于2月,3月等帐户123的记录。我想要列出这个帐户缺少的月份,如下:

ReportMonth, AccountID, MissingSince, LastStatus

到目前为止,通过使用左连接并搜索空值,我已经能够找到与上个月相比下降的帐户:

left outer join #StatusCodes b on a.AccountID= b.AccountID
and datediff(m,0,a.ReportMonth) = datediff(m,0,b.ReportMonth)-1
...
and b.AccountID is null

但这显然只适用于一个月。

SQL Fiddle for what I'm doing now

应该在2月到4月之间为报告月输出1,在5月之后输出2。即:

ReportMonth | Dropped Accounts
Jan 2014.   | 0
Feb 2014.   | 1
March 2014. | 1
Apr 2014.   | 1
May 2014.   | 2
Jun 2014.   | 2

Updated SQLFiddle< - 我的最终实施。小数据集不公平,但它有效!

1 个答案:

答案 0 :(得分:1)

这应该让你开始......

隔离月/帐户的所有distinct值,然后cross apply,然后与reportHist表进行比较,并通过CASE填充1/0以查找缺失的行和SUM()结果。

小提琴here

IF OBJECT_ID('TEMPDB..#reportHist') IS NOT NULL 
    DROP TABLE #reportHist

CREATE TABLE #reportHist
    (
     ReportMonth datetime, 
     AccountID varchar(20), 
     Status varchar(30)
    );

INSERT INTO #reportHist
(ReportMonth, AccountID, Status)
VALUES
('1-1-2014','123','Good'),
('1-1-2014','999','Good'),
('2-1-2014','999','Bad'),
('3-1-2014','999','Good'),
('4-1-2014','999','Good');

;WITH DistinctAccount
AS
(
SELECT DISTINCT AccountID
FROM #reportHist
)
, DistinctMonth
AS
(
SELECT DISTINCT ReportMonth
FROM #reportHist
)

SELECT DM.ReportMonth, SUM(CASE WHEN RH.AccountID IS NULL THEN 1 ELSE 0 END) AS [Dropped Accounts]
FROM DistinctAccount DA
CROSS APPLY DistinctMonth DM
LEFT OUTER JOIN #reportHist RH
   ON DA.AccountID = RH.AccountID
   AND DM.ReportMonth = RH.ReportMonth  
GROUP BY DM.ReportMonth
相关问题