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);