SQL窗口函数/ rownum / order by

时间:2017-07-17 14:21:38

标签: sql sql-server-2005

我试图查看客户请求重新激活其互联网帐户的频率。

问题是,我们捕获一组有限的数据进行分组。所以我的数据集如下。

我试图从第一次创建重新激活请求开始计数,直到第一次完成它已完成,一旦完成,完成请求完成所需的天数并计算NON的数量在那段时间之间发生的完成和SENT状态。

下面是示例数据的图像以及表的sql。希望有人能提供一些帮助。 (使用SQL Server 2005兼容性)

IMAGE OF PROBLEM AND WHAT I WANT TO ACHIEVE

CREATE TABLE #temp
(
Identifier varchar(20)NOT NULL
,CreatedDate DATETIME NOT NULL
,CompletedDate DATETIME NOT NULL
,SN_Type varchar(20) NOT NULL
,SN_Status varchar(20) NOT NULL
)
;

INSERT INTO #temp
VALUES('64074558792','20160729','20160805','Re-Activattion','SENT');
INSERT INTO #temp
VALUES('64074558792','20160810','20160810','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES('64074558792','20160812','20160812','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES('64074558792','20160811','20160811','Re-Activattion','COMP');
INSERT INTO #temp
VALUES('64074558792','20160811','20160813','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES ('61030203647','20160427','20160427','Re-Activattion', 'COMP');
INSERT INTO #temp
VALUES('61030203647','20160425','20160425','Re-Activattion', 'N-CO');
INSERT INTO #temp
VALUES('61030203647','20160422','20160422','Re-Activattion', 'N-CO');
INSERT INTO #temp
VALUES('61030203647','20170210','20170210','Re-Activattion', 'COMP');
INSERT INTO #temp
VALUES('61030203688','20170409','20170210','Re-Activattion', 'SENT');
INSERT INTO #temp
VALUES('61030203699','20170409','20170210','De-Activattion', 'COMP');

1 个答案:

答案 0 :(得分:0)

我不确定这是否满足您的要求,

select identifier,count(1) as cnt,sum(case when sn_status = 'N-CO' then 1 else 0 end) as non_com_cnt ,sum(case when sn_status = 'SENT' then 1 else 0 end) as
 sent_cnt, datediff(dd,min(case when sn_status = 'SENT' then createddate end),max(case when sn_status = 'COMP' then completeddate end)) as diff,min(case when sn_status = 'SENT' then createddate end) as start_date,max(case when sn_status = 'COMP' then completeddate end)  from #temp where sn_type = 'Re-Activattion' group by identifier;