从分组列中选择最大值的SQL问题

时间:2016-08-03 03:06:44

标签: sql sql-server

大家好我实际上有问题。

  select * from Insurance_Plan;
  select * from Enroll;
  select * from Patient;

这三个是我数据库中的表。现在我必须获得最多患者登记者的保险计划,并为该计划,其名称,所需的共付金额和患者登记者的数量。

到目前为止,我已经完成了那部分:

 Select I.Insurance_Name,Max(I.Insurance_Copayment_Amount) As 
   Copayment_Amount,count(P.Patient_ID) As Number_Of_Patients
   From Insurance_Plan as I inner Join 
   Enroll AS E on I.Insurance_Plan_ID=E.Insurance_Plan_ID
   inner join Patient as P on P.Patient_ID=E.Patient_ID
   group by Insurance_Name 

结果我得到了输出:          enter image description here

现在我想只显示最多登记患者的保险计划,这是所示输出中的第二行。我试图使用Max函数,但得到错误。它必须在一个有效的查询中完成。

2 个答案:

答案 0 :(得分:0)

 Select top (1) I.Insurance_Name,Max(I.Insurance_Copayment_Amount) As 
   Copayment_Amount,count(P.Patient_ID) As Number_Of_Patients
   From Insurance_Plan as I inner Join 
   Enroll AS E on I.Insurance_Plan_ID=E.Insurance_Plan_ID
   inner join Patient as P on P.Patient_ID=E.Patient_ID
   group by Insurance_Name
   order by count(P.Patient_ID) desc 

答案 1 :(得分:0)

尝试添加

<style>
  form  {
    width: 200px;
    margin: 0 auto;
  }

  input {
    display: block;
    margin: 5px 0;
  }
</style>

<form name="form1" method="POST" action="/">
  <h1>Client Login</h1>

  <input name="myusername" type="text" id="myusername" placeholder="Company Name" size="24">
  <input name="mypassword" type="password" id="mypassword" placeholder="password" size="25">
  <input name="Submit" type="submit" class="submit_button" value="Login">
</form>

在查询结束时。

Here you will find a good example for having-max.