SQL Server:在结果集中查找最大值

时间:2015-11-19 23:38:46

标签: sql sql-server subquery max

我有这个代码,我很难理解它为什么不起作用。我已经搜索了解决方案,这实际上是我的代码结果如何,但它只是不正常...任何帮助将不胜感激。

我要做的是为每个客户选择一条记录。选择的记录应该是债务人余额最高的记录。相反,我得到所有债务人的余额。几乎不喜欢它不将它们分组回客户端......

SELECT  
    Debtorness.ClientName,
    Debtorness.DebtorName,
    MAX(Debtorness.DFB)
FROM
    (SELECT
         Clients.Name AS ClientName, 
         Debtors.Name AS DebtorName,
         (CalcAging.FundedBalance) AS DFB
     FROM   
         Clients 
     INNER JOIN
         CalcAging ON Clients.ClientKey = CalcAging.ClientKey 
     INNER JOIN
         Debtors ON CalcAging.DebtorKey = Debtors.DebtorKey 
     INNER JOIN
         CalcClient ON Clients.ClientKey = CalcClient.ClientKey
     WHERE
         Clients.Inactive='0'
     GROUP BY
         Clients.Name, Debtors.Name, CalcAging.FundedBalance, 
         CalcAging.MasterDebtorKey) AS Debtorness
GROUP BY 
    Debtorness.ClientName, Debtorness.DebtorName, Debtorness.DFB
ORDER BY 
    Debtorness.ClientName ASC

我得到的示例输出:

Client1 | Debtor23 | Balance    
Client1 | Debtor47 | Balance
Client1 | Debtor14 | Balance  
Client2 | Debtor72 | Balance
Client2 | Debtor30 | Balance

等......对所有客户而言。再一次,我想看到所有客户,但我只想让那个客户的余额最高的债务人......谢谢!

2 个答案:

答案 0 :(得分:2)

使用 row_number()

WITH cte as (
    SELECT
        Clients.Name AS ClientName, 
        Debtors.Name AS DebtorName,
        CalcAging.FundedBalance AS DFB,
        ROW_NUMBER() over 
           (PARTITION BY Clients.Name ORDER BY CalcAging.FundedBalance DESC)  as rn
    FROM    
        Clients INNER JOIN
        CalcAging ON Clients.ClientKey = CalcAging.ClientKey INNER JOIN
        Debtors ON CalcAging.DebtorKey = Debtors.DebtorKey INNER JOIN
        CalcClient ON Clients.ClientKey = CalcClient.ClientKey
    WHERE
        Clients.Inactive='0'
)
SELECT *
FROM cte
WHERE rn = 1;

答案 1 :(得分:0)

快速而肮脏的解决方案是对当前结果进行选择。这是继续工作与您已经拥有的内容以及您已经知道的方式

结果

    select clientname,debtorname,balance_column from (SELECT  Debtorness.ClientName,
    Debtorness.DebtorName,
    MAX(Debtorness.DFB)
FROM    (

SELECT
    Clients.Name AS ClientName, 
    Debtors.Name AS DebtorName,
    (CalcAging.FundedBalance) AS DFB
FROM    
    Clients INNER JOIN
    CalcAging ON Clients.ClientKey = CalcAging.ClientKey INNER JOIN
    Debtors ON CalcAging.DebtorKey = Debtors.DebtorKey INNER JOIN
    CalcClient ON Clients.ClientKey = CalcClient.ClientKey
WHERE
    Clients.Inactive='0'
 GROUP BY
    Clients.Name, Debtors.Name, CalcAging.FundedBalance, CalcAging.MasterDebtorKey
) AS Debtorness
GROUP BY Debtorness.ClientName, Debtorness.DebtorName, Debtorness.DFB
ORDER BY Debtorness.ClientName Asc) group by clientname having a.balance_column = Max(a.balance_column)