来自T-SQL查询的原始列名称,在原始列名称重新分类后生成列

时间:2016-03-30 19:14:26

标签: sql-server tsql

我有一个相对标准的sql查询,其中包含多个表连接,以及在将贷款重新分类为ORE(其他房地产所有权)后所有与贷款相关的子句。我正在尝试列出其中一个ORIGINAL字段(类别)的值,该字段现已更改为ORE。

对于'消费者'说原始类别为1但是一旦贷款转到ORE,该类别就是12,其中包括所有原始类别(1,2,3,4)

存在问题 - 我需要显示ORE贷款,仅表示类别1& 2.我没有尝试过任何工作 - 我假设因为查询底部的where子句指定我需要各种字段,这些字段都与ORE状态相关但不与原始类别相关。我已经尝试了子查询(不要工作,因为他们是'以上'主要查询&where;以及... ...

非常感谢任何一般指导。这是查询及其下面的子查询:

SELECT
A.ACCTNO
E.SNAME,
B.OREO_ID,
A.OREODATE,
GC.CATEGORY
FROM
DBO.LOAN_SYSTEM AS A
LEFT OUTER JOIN DBO.ORE AS B
ON A.OREO_ID = B.OREO_ID
LEFT OUTER JOIN DBO.LOAN_TITLE AS C
ON A.OREO_ID = C.OREO_ID AND C.SEQ = 1
LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL) AS D
ON A.OREO_ID = D.OREO_ID
LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC
ON E.[GROUP] = GC.GROUP_CODE
WHERE
D.FC_ID IS NOT NULL AND C.FORECLOSUREDATE IS NOT NULL AND GC.CATEGORY IN (1,2) --DOESN'T WORK BECAUSE ONCE IN OREO = 12
AND
E.STATUS NOT IN (2,8)

--SUBQUERY GETS ORIGINAL CATEGORY
SELECT
B.ACCTNO, C.CATEGORY
FROM DBO.LOAN_SYSTEM A
LEFT OUTER JOIN DBO.LOAN_DAILY_INFO B
ON B.ACCTNO = A.ACCTNO
AND B.TYPE = A.TYPE
LEFT OUTER JOIN DBO.TBL_GROUP_CODES C
ON C.GROUP_CODE = B.[GROUP]
LEFT OUTER JOIN DBO.TBL_LOAN_TYPES D
ON D.TYPE = A.TYPE
WHERE B.STATUS NOT IN (2,8)
AND C.CATEGORY IN (1,2)

1 个答案:

答案 0 :(得分:0)

我不是100%肯定你在这里要做什么..但你可能需要在这里使用EXISTS。

SELECT  A.ACCTNO,
        E.SNAME,
        B.OREO_ID,
        A.OREODATE,
        GC.CATEGORY
FROM    DBO.LOAN_SYSTEM AS A
        LEFT OUTER JOIN DBO.ORE AS B ON A.OREO_ID = B.OREO_ID
        LEFT OUTER JOIN DBO.LOAN_TITLE AS C ON A.OREO_ID = C.OREO_ID
                                               AND C.SEQ = 1
        LEFT OUTER JOIN (SELECT * FROM DBO.LOAN_FC WHERE ISDELETED = 0 AND ISDISMISSED IS NULL
                        ) AS D ON A.OREO_ID = D.OREO_ID
        LEFT OUTER JOIN DBO.TBL_GROUP_CODES GC ON D.[GROUP] = GC.GROUP_CODE
WHERE   D.FC_ID IS NOT NULL
        AND C.FORECLOSUREDATE IS NOT NULL
        AND EXISTS (
            SELECT  1
            FROM    DBO.LOAN_DAILY_INFO F
                    JOIN DBO.TBL_GROUP_CODES G ON G.GROUP_CODE = F.[GROUP]
            WHERE   F.STATUS NOT IN (2,8)
                    AND G.CATEGORY IN (1,2)
                    AND F.ACCTNO = A.ACCTNO
                    AND F.TYPE = A.TYPE 
        ) 
        AND D.STATUS NOT IN (2,8)