Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 dummy ask for help

Author  Topic 

kkbearjj
Starting Member

4 Posts

Posted - 2015-04-10 : 15:11:46
Hi, I need help to finish my project ASAP. My task is to figure out defects in this Loan_Status_Tbl.

When Current_Principal= 0, Loan_status should be populated from previous records. For example, when Loan_Nbr 00001's current_Principal=0, it's loan_status is not populated from it's 2010-12-30 record, and 00002,00003 are good. I want to know which items are not good, and report the results to engineer to modify the wrong record in DW.



ID LOAN_NBR CURRENT_PRINCIPAL LOAD_DT LOAN_STATUS

1 00001 1000 2010-12-5 APPROVED

2 00001 800 2010-12-30 APPROVED

3 00001 0 2011-3-1 NULL

4 00002 500 2012-5-1 APPROVED

5 00002 0 2012-6-12 APPROVED

6 00003 850 2012-1-1 Pending

7 00003 500 2012-2-1 Approved

8 00003 0 2012-3-2 Approved

stepson
Aged Yak Warrior

545 Posts

Posted - 2015-04-11 : 01:20:27
the same as http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=200763

;WITH cteSample
AS(SELECT ID,LOAN_NBR,CURRENT_PRINCIPAL,LOAD_DT,LOAN_STATUS
FROM (VALUES(1,'00001',1000,'2010-12-5','APPROVED')
,(2,'00001',800,'2010-12-30','APPROVED')
,(3,'00001',0,'2011-3-1', NULL)
,(4,'00002',500,'2012-5-1','APPROVED')
,(5,'00002',0,'2012-6-12','APPROVED')
,(6,'00003',850,'2012-1-1','Pending')
,(7,'00003',500,'2012-2-1','Approved')
,(8,'00003',0,'2012-3-2','Approved')
) A (ID,LOAN_NBR,CURRENT_PRINCIPAL,LOAD_DT,LOAN_STATUS)
)
SELECT ID
,LOAN_NBR
,CURRENT_PRINCIPAL
,LOAD_DT
,A.LOAN_STATUS
,B.LOAN_STATUS
FROM cteSample AS A
OUTER APPLY
(
SELECT TOP(1)
B.LOAN_STATUS
FROM cteSample AS B
WHERE
A.LOAN_NBR = B.LOAN_NBR
AND A.ID > B.ID
ORDER BY B.ID DESC
)B
WHERE
A.CURRENT_PRINCIPAL =0
AND ( (A.LOAN_STATUS <> B.LOAN_STATUS)
OR
(A.LOAN_STATUS IS NULL AND B.LOAN_STATUS IS NOT NULL)
)
ORDER BY A.ID



sabinWeb MCP
Go to Top of Page

stepson
Aged Yak Warrior

545 Posts

Posted - 2015-04-11 : 02:08:30
If you are using SQL 2012, then you can use LAG function

SELECT
ID
,LOAN_NBR
,CURRENT_PRINCIPAL
,LOAD_DT
,LOAN_STATUS
,LOAN_STATUS_PREV
FROM
(
SELECT ID
,LOAN_NBR
,CURRENT_PRINCIPAL
,LOAD_DT
,A.LOAN_STATUS
,LAG(A.LOAN_STATUS ,1,NULL) OVER(PARTITION BY LOAN_NBR ORDER BY ID) AS LOAN_STATUS_PREV
FROM cteSample AS A
)A
WHERE
A.CURRENT_PRINCIPAL =0
AND ( (A.LOAN_STATUS <> A.LOAN_STATUS_PREV)
OR
(A.LOAN_STATUS IS NULL AND A.LOAN_STATUS_PREV IS NOT NULL)
)
ORDER BY A.ID



sabinWeb MCP
Go to Top of Page
   

- Advertisement -