这是我的贷款表的示例:
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
如果为Loanno所述LoanId不同的是,即,(1,2,3,4,5),那么我来填充一个称为字段 LoanIndex为“6”。
Loanno
LoanId
LoanIndex
否则,如果贷款编号的Loanid值都相同,即全部为1或全部为2,那么我必须填充LoanIndex为“ 1”或“ 2”。
Loanid
我的最终输出应如下所示:
Loanno LoanIndex 1001045 6 1001046 1 1001047 2
从查询开始,该查询为您提供Loanno和的所有唯一组合LoanID。
LoanID
SELECT DISTINCT Loanno, LoanID FROM [Loan Table]
然后使用该SQL作为子查询,并LoanID为每个查询计算唯一值的数量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
最后,将其与your连接,[Loan Table]并使用一个IIf()表达式,如果CountOfLoanID>> 1,则返回6 LoanID。
[Loan Table]
IIf()
CountOfLoanID
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);