简体   繁体   中英

SQL Query keeps returning multiple rows

I wrote this SQL Query to get the remaining benefits for a particular patient, expecting it to return a single row since the patient id is unique, but it keeps returning multiple rows. How do I fix this? DBMS is MySql

 select Plan.pBenefitMax - sum(Transaction.employerTotal) as RemainingBenefit
 from Patient
 inner join Plan on Patient.pPlanId = Plan.planId
 inner join Transaction on Patient.patientId = Transaction.tPatientId
  where Patient.patientId = 1
 Group by Plan.pBenefitMax;

If this does not get a single row, you either have duplicate PatientId values or the PatientId is linked to more than one Plan.

  SELECT Plan.pBenefitMax - 
         (SELECT SUM(`Transaction`.employerTotal) 
            FROM `Transaction` 
           WHERE `Transaction`.tPatientId = Patient.patientId) 
         AS RemainingBenefit
    FROM Patient
    JOIN Plan ON Patient.pPlanId = Plan.planId
   WHERE Patient.patientId = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM