使用两个子查询的结果来计算比率

时间:2014-01-31 09:53:32

标签: sql sql-server subquery

我有以下查询

SELECT 'Active Borrowers per Loan Officer' AS PERFORMANCE_RATIOS,
    (
        SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
        FROM LD_LOANS_AND_DEPOSITS L
        WHERE REPORT_DATE = (
                SELECT MIN(REPORT_DATE)
                FROM LD_LOANS_AND_DEPOSITS
                )
        ) AS RATIO1,
    (
        SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
        FROM LD_LOANS_AND_DEPOSITS L
        WHERE REPORT_DATE = (
                SELECT MAX(REPORT_DATE)
                FROM LD_LOANS_AND_DEPOSITS
                )
        ) AS RATIO2,
    (
        (
            SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
            FROM LD_LOANS_AND_DEPOSITS L
            WHERE REPORT_DATE = (
                    SELECT MAX(REPORT_DATE)
                    FROM LD_LOANS_AND_DEPOSITS
                    )
            ) - (
            SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
            FROM LD_LOANS_AND_DEPOSITS L
            WHERE REPORT_DATE = (
                    SELECT MIN(REPORT_DATE)
                    FROM LD_LOANS_AND_DEPOSITS
                    )
            )
        ) / (
        SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
        FROM LD_LOANS_AND_DEPOSITS L
        WHERE REPORT_DATE = (
                SELECT MIN(REPORT_DATE)
                FROM LD_LOANS_AND_DEPOSITS
                )
        ) * 100 AS CHANGE,
    (
        SELECT MIN(REPORT_DATE)
        FROM LD_LOANS_AND_DEPOSITS
        ) AS REPORT_DATE1,
    (
        SELECT MAX(REPORT_DATE)
        FROM LD_LOANS_AND_DEPOSITS
        ) AS REPORT_DATE2

我需要做的是在外面使用Ratio1 / Ratio2,而不是必须重复返回theese 2值的整个sql代码。我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是你的答案

SELECT PERFORMANCE_RATIOS, RATIO1, RATIO2, RATIO1 - RATIO2 AS SUBTRACT, RATIO1 * RATIO2 AS Multiply
FROM (
SELECT 'Active Borrowers per Loan Officer' AS PERFORMANCE_RATIOS,
    (
        SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
        FROM LD_LOANS_AND_DEPOSITS L
        WHERE REPORT_DATE = (
                SELECT MIN(REPORT_DATE)
                FROM LD_LOANS_AND_DEPOSITS
                )
        ) AS RATIO1,
    (
        SELECT count(DISTINCT L.CUSTOMER_ID) / COUNT(DISTINCT L.MIS_ACCT_OFFICER) AS RATIO
        FROM LD_LOANS_AND_DEPOSITS L
        WHERE REPORT_DATE = (
                SELECT MAX(REPORT_DATE)
                FROM LD_LOANS_AND_DEPOSITS
                )
        ) AS RATIO2
) Table