1

嗨,这是我使用 Loandetails 的表

Loanno  Balance amount  DueDATE
1001045 308731.770000   12/31/99
1001045 2007700.740000  12/31/99
1001045 3087318905.770000   11/01/99
1001045 308731.770000   12/31/99

我必须选择LoannoDueDate基于maximum value of Balance Amount. Loanno不是唯一的。请帮我解决这个问题。

4

4 回答 4

1

在 SQLServer2005+ 中可以使用ROW_NUMBER排名函数

 ;WITH cte AS
 (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY Loanno ORDER BY [Balance Amount] DESC) AS rn
  FROM dbo.your_tableName
  )
  SELECT Loanno, DueDate
  FROM cte
  WHERE rn = 1
于 2013-05-24T08:39:03.760 回答
1

这将起作用,子查询拉回 Balance 字段的最大值,然后用于查找具有相同值的一个(或多个)记录。

select LoanNo, DueDate 
from _LoanData 
where Balance = (
    select max(Balance)
    from _loandata
    )

或者这个,它从按余额降序排列的列表中提取前 1 个(第一条记录)。性能方面,这更慢。

select top 1 LoanNo, DueDate, Balance
from _LoanData 
order by Balance desc

祝你好运。

于 2013-05-24T08:41:04.347 回答
0

尝试这个:

SELECT L.Loanno, L.Balanceamount, L.DueDate
     FROM dbo.Loan L 
     INNER JOIN 
         (
          SELECT Loanno, MAX(Balancemount) as MaxBalance FROM dbo.Loan
             GROUP BY LoanNo
         ) SUB ON L.Loanno = SUB.Loanno AND L.Balanceamount = SUB.MaxBalance

子查询返回Maximum balance每个 LoanNo(无论日期如何)当连接回您的原始表时,您会留下 LoanNo、最大余额和到期日期。

好的,刚刚在 MS Access 中测试了下面的查询,它工作得很好,Table1用您的实际表名替换:

SELECT T.LoanNo, T.DueDate, T.BalanceAmount
 FROM Table1 As T
  INNER JOIN (
     SELECT T.Loanno, Max([T.Balanceamount]) AS MaxBalance
     FROM Table1 as T
     GROUP BY T.Loanno) SUB ON T.LoanNo = SUB.LoanNo AND T.BalanceAmount = SUB.MaxBalance
于 2013-05-24T08:38:34.673 回答
-1

试试这个-:

SELECT Loanno ,DueDate 
FROM
     (SELECT Loanno ,DueDate , MAX(Balance amount) BAL_AMT
      FROM Loandetails 
      GROUP BY Loanno ,DueDate 
     )
于 2013-05-24T08:39:56.150 回答