Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum union calculated value in SQL

I have two SELECT statements that I'd like to sum. Both queries work fine but I'm not able to SUM the output of total. I tried following this question but unable to SUM by wrapping the query in select id, sum(amount) from ( )

SELECT "patient_profiles"."id", count(distinct recommendations.id) AS total
FROM "patient_profiles" 
  LEFT OUTER JOIN 
  "recommendations" ON "recommendations"."patient_profile_id" = "patient_profiles"."id" 
GROUP BY "patient_profiles"."id"

UNION

SELECT "patient_profiles"."id", count(distinct patient_profile_potential_doctors.id) AS total
FROM "patient_profiles" 
  LEFT OUTER JOIN "patient_profile_potential_doctors" ON "patient_profile_potential_doctors"."patient_profile_id" = "patient_profiles"."id"       
GROUP BY "patient_profiles"."id"
like image 811
user2954587 Avatar asked Sep 12 '25 02:09

user2954587


1 Answers

    Select ID, sum(Total) from  
      (
        SELECT "patient_profiles"."id" [ID], count(distinct recommendations.id) AS total
        FROM "patient_profiles" 
          LEFT OUTER JOIN 
          "recommendations" ON "recommendations"."patient_profile_id" = "patient_profiles"."id" 
        GROUP BY "patient_profiles"."id"

        UNION

        SELECT "patient_profiles"."id" [ID], count(distinct patient_profile_potential_doctors.id) AS total
        FROM "patient_profiles" 
          LEFT OUTER JOIN "patient_profile_potential_doctors" ON "patient_profile_potential_doctors"."patient_profile_id" = "patient_profiles"."id"       
        GROUP BY "patient_profiles"."id"
) x
    group by ID
like image 184
Herman Avatar answered Sep 13 '25 15:09

Herman