嗨,这是我使用说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
我必须根据Loanno
选择DueDate
和maximum value of Balance Amount
。
Loanno
并不是唯一的。请帮我解决这个问题。
答案 0 :(得分: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
答案 1 :(得分: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
祝你好运。
答案 2 :(得分: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
子查询为每个LoanNo返回Maximum balance
(无论日期如何)
当您加入原始表格时,您将获得贷款,最高余额和到期日期。
好的,只是在MS Acccess中测试了下面的查询,它运行得很好,用您的实际表名替换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
答案 3 :(得分:-1)
试试这个 - :
SELECT Loanno ,DueDate
FROM
(SELECT Loanno ,DueDate , MAX(Balance amount) BAL_AMT
FROM Loandetails
GROUP BY Loanno ,DueDate
)