Question

Here is a sample of my Loan table:

Loanno  Balance amount  LoanID
1001045 308731.770000   1
1001045 2007700.740000  2
1001045 3087318905.770  3
1001045 308731.770000   4
1001046 306589.67       1
1001046 456321.23       1
1001046 6932542.89      1
1001047 582563.56       2
1001047 965421.34       2
  1. If for a Loanno the LoanId is different, i.e (1,2,3,4,5), then I have to populate a field called LoanIndex as '6'.

  2. Otherwise if for a Loannumber the Loanid values are all the same, i.e all 1's or all 2's, then I have to populate LoanIndex as either '1' or '2'.

My final output should look like this:

Loanno   LoanIndex
1001045    6
1001046    1
1001047    2
Was it helpful?

Solution

Start with a query which gives you all unique combinations of Loanno and LoanID.

SELECT DISTINCT
    Loanno,
    LoanID
FROM [Loan Table]

Then use that SQL as a subquery and compute the count of unique LoanID values for each Loanno.

SELECT
    distinct_rows.Loanno,
    Count(distinct_rows.LoanID) AS CountOfLoanID
FROM
    (
        SELECT DISTINCT
            Loanno,
            LoanID
        FROM [Loan Table]
    ) AS distinct_rows
GROUP BY distinct_rows.Loanno

Finally join that with your [Loan Table] and use an IIf() expression which returns 6 if CountOfLoanID is > 1, or LoanID otherwise.

SELECT
    lt.Loanno,
    IIf(counts.CountOfLoanID>1, 6, lt.LoanID) AS LoanIndex
FROM
    [Loan Table] AS lt
    INNER JOIN
        (
            SELECT
                distinct_rows.Loanno,
                Count(distinct_rows.LoanID) AS CountOfLoanID
            FROM
                (
                    SELECT DISTINCT
                        Loanno,
                        LoanID
                    FROM [Loan Table]
                ) AS distinct_rows
            GROUP BY distinct_rows.Loanno
        ) AS counts
    ON lt.Loanno = counts.Loanno
GROUP BY
    lt.Loanno,
    IIf(counts.CountOfLoanID>1, 6, lt.LoanID);

OTHER TIPS

I would create a few queries:

1 query has all the unique loanno / loanid combinations

SELECT LoanTable.LoanNo, LoanTable.LoanID
FROM LoanTable
GROUP BY LoanTable.LoanNo, LoanTable.LoanID;

The next query, built on the 1st one, has the count of loanid values for each loanno

SELECT Q_LoanID.LoanNo, Count(Q_LoanID.LoanID) AS [Count]
FROM Q_LoanID
GROUP BY Q_LoanID.LoanNo;

The 3rd query, built on the original data and the 2nd query, uses the count from the 2nd query (1 if all the loanid's are the same, or >1 if there are multiples) to perform the data updates you need

SELECT LoanTable.LoanNo, IIf([count]>1,"6",[LoanTable].[LoanID]) AS LoanID, Sum(LoanTable.Balance) AS Balance
FROM LoanTable INNER JOIN Q_LoanID_count ON LoanTable.LoanNo = Q_LoanID_count.LoanNo
GROUP BY LoanTable.LoanNo, IIf([count]>1,"6",[LoanTable].[LoanID]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top