1

这是我的贷款表的示例:

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. 如果 a不同,LoannoLoanId(1,2,3,4,5),那么我必须填充一个名为 LoanIndex“6”的字段。

  2. 否则,如果 Loannumber 的Loanid值都相同,即全为 1 或全为 2,那么我必须填充LoanIndex为“1”或“2”。

我的最终输出应如下所示:

Loanno   LoanIndex
1001045    6
1001046    1
1001047    2
4

2 回答 2

1

Loanno从一个查询开始,它为您提供和的所有独特组合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

最后将它与您的连接[Loan Table]并使用一个IIf()表达式,如果CountOfLoanID大于 1,则返回 6,LoanID否则。

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);
于 2013-05-25T14:20:18.607 回答
0

我会创建一些查询:

1 个查询具有所有唯一的 loanno / loanid 组合

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

建立在第一个查询上的下一个查询具有每个 loanno 的 loanid 值的计数

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

第 3 次查询基于原始数据和第 2 次查询,使用来自第 2 次查询的计数(如果所有的 loanid 都相同,则为 1,如果有多个,则 >1)来执行您需要的数据更新

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]);
于 2013-05-24T12:21:20.980 回答