在特定列SQL Server中选择具有最大值的行

时间:2014-04-04 09:05:53

标签: sql sql-server

我过去几天一直在做一个学校项目,我选择在DVD俱乐部数据库上工作。我有六张桌子,但对于这个问题,只有两张是相关的。客户表和贷款表。所以,我想要做的就是为每个客户计算到目前为止他已经提供了多少贷款,并且最多可以向客户提供最大数量的贷款,因此他可以在下个月获得免费DVD奖励。这是我编写的代码,但它没有选择特定的客户端,它显示了具有特定客户的最大贷款数量的所有客户:

SELECT tblClients.Client_ID, MAX(x.Number_Of_Loans) AS MAX_NOL
FROM 
(
SELECT COUNT(tblLoans.Client_ID) AS Number_Of_Loans 
FROM tblClients, tblLoans WHERE tblClients.Client_ID=tblLoans.Client_ID 
GROUP BY tblLoans.Client_ID
)x, tblClients, tblLoans
WHERE tblClients.Client_ID=tblLoans.Client_ID
GROUP BY tblClients.Client_ID, tblClients.Given_Name, 
tblClients.Family_Name, tblClients.Phone, tblClients.Address, tblClients.Town_ID

2 个答案:

答案 0 :(得分:2)

使用以下

SELECT TOP 1 tblClients.Client_ID,COUNT(tblLoans.Client_ID) AS MAX_NOL 
FROM tblClients, tblLoans 
WHERE tblClients.Client_ID=tblLoans.Client_ID 
GROUP BY tblClients.Client_ID
ORDER BY COUNT(tblLoans.Client_ID) DESC 

答案 1 :(得分:1)

您可以使用单个聚合GROUP执行此操作,由客户订购最大贷款:

SELECT TOP 1 tblClients.Client_ID, tblClients.Given_Name, tblClients.Family_Name, 
       tblClients.Phone, tblClients.Address, tblClients.Town_ID, 
       COUNT(x.Number_Of_Loans) AS MAX_NOL
FROM
   tblClients INNER JOIN tblLoans 
     ON tblClients.Client_ID=tblLoans.Client_ID
GROUP BY tblClients.Client_ID, tblClients.Given_Name, tblClients.Family_Name,
         tblClients.Phone, tblClients.Address, tblClients.Town_ID
ORDER BY MAX_NOL DESC;

客户端中的所有选定列都需要包含在GROUP中,我建议您使用JOINs代替WHERE加入。

修改
可能更整洁的是将ClientId的确定与最多贷款分开,并关注获取客户端的其余数据,如此(而不是多列中的笨拙GROUP BY):< / p>

SELECT c.Client_ID, c.Given_Name, c.Family_Name, 
       c.Phone, c.Address, c.Town_ID, 
       x.MaxLoans
FROM
   tblClients c
   INNER JOIN
     (SELECT TOP 1 tblClients.Client_ID, COUNT(tblLoans.Client_ID) AS MaxLoans
      FROM tblClients 
        INNER JOIN tblLoans 
        ON tblClients.Client_ID=tblLoans.Client_ID
      GROUP BY tblClients.Client_ID
      ORDER BY MaxLoans DESC) x
     ON c.Client_ID = x.Client_ID;