MySQL查询从另一个查询的结果中查找总和

时间:2015-04-10 04:20:53

标签: mysql

这是我的SQL查询:

SELECT (
    SELECT COUNT(appointment_doctor) FROM appointment
    JOIN doctor ON appointment.appointment_doctor = doctor.doctor_id
    WHERE appointment_doctor = doctor_id
) * doctor_payment_rate AS fees FROM doctor
JOIN doctor_payment ON doctor.doctor_id=doctor_payment.doctor_payment_doctor

结果:

  

费用500 1000 615 11615 1160 615 1610 285 660 220 3835 215 615 555 555 1065 1110 620 445 220 660 625 60 1715 615 10 115 615 60 625 60 330 615 625 720 625 615 670 615 500 615 500

我希望所有这些值的总和为total_fee

3 个答案:

答案 0 :(得分:0)

   select
   sum(select
      count(appointment_doctor) 
   from
      appointment 
   join
      doctor 
         on    appointment.appointment_doctor= doctor.doctor_id 
   where
      appointment_doctor=doctor_id)*doctor_payment_rate as 'Total fee' 
from
   doctor     
join
   doctor_payment 
      on doctor.doctor_id=doctor_payment.doctor_payment_doctor

答案 1 :(得分:0)

尝试此查询:

SELECT SUM (
    (SELECT COUNT(appointment_doctor) FROM appointment
    JOIN doctor ON appointment.appointment_doctor = doctor.doctor_id
    WHERE appointment_doctor = doctor_id) * doctor_payment_rate))
    AS total_fee
    FROM doctor
    JOIN doctor_payment
    ON doctor.doctor_id=doctor_payment.doctor_payment_doctor

答案 2 :(得分:0)

使用mysql sum函数SUM()函数返回数值列的总和

SELECT SUM (
    SELECT (
        SELECT COUNT(appointment_doctor) FROM appointment
        JOIN doctor ON appointment.appointment_doctor = doctor.doctor_id
        WHERE appointment_doctor = doctor_id
    )