0

I am working on a following query and not able to figure out one thing.The result of the main query at bottom are in the following way:-

Institute name || Total users || Students || teachers || professionals || Email || Country of Teacher.**

I want to add the institute of the country as a second column. Table name - countries Primary Key - Id

The query is simple to understand. How should i proceed or accommodate the following query into the big one where I can get the final result as:-

Institute name || Country name of institute || Total users || Students || teachers || professionals || Email || Country of Teacher.**

 select  pl.name AS institute_name, c.name as country_name
 from profiles p , places pl , countries c
 where pl.id = p.place_id and p.country_id = c.id
 and pl.formatted_address != ''  

// The main query Starts here

   SELECT t.institute_name, SUM(t.total_users), SUM(t.students), SUM(t.teachers), SUM(t.professionals), MAX(t.teacher_emails), MAX(t.teacher_countries)

 FROM

  ((SELECT pl.name AS institute_name, COUNT(ut.classification) AS total_users, COUNT(ut.classification) AS students, 0 AS teachers, 0 AS professionals, NULL AS teacher_emails, NULL AS teacher_countries

       FROM profiles p , places pl , countries c ,user_types ut, users u
          WHERE pl.id = p.place_id AND
          ut.classification = 'student' AND
          p.country_id = c.id AND
          p.user_type_id = ut.id
          AND p.user_id = u.id
          AND DATE(u.created_at) >= '2015-10-02 08:00:00'
          AND formatted_address != '' 
          GROUP BY pl.name, ut.classification)

           ) AS t

  GROUP BY t.institute_name
   HAVING SUM(t.total_users) >= '10'
   ORDER BY t.total_users DESC
Rish
  • 25
  • 6

1 Answers1

0

Try this

   SELECT t.institute_name, t.country_name, SUM(t.total_users), SUM(t.students), SUM(t.teachers), SUM(t.professionals), MAX(t.teacher_emails), MAX(t.teacher_countries)

 FROM

  ((SELECT pl.name AS institute_name, c.name as country_name, COUNT(ut.classification) AS total_users, COUNT(ut.classification) AS students, 0 AS teachers, 0 AS professionals, NULL AS teacher_emails, NULL AS teacher_countries

       FROM profiles p , places pl , countries c ,user_types ut, users u
          WHERE pl.id = p.place_id AND
          ut.classification = 'student' AND
          p.country_id = c.id AND
          p.user_type_id = ut.id
          AND p.user_id = u.id
          AND DATE(u.created_at) >= '2015-10-02 08:00:00'
          AND formatted_address != '' 
          GROUP BY pl.name, ut.classification)

           ) AS t

  GROUP BY t.institute_name
   HAVING SUM(t.total_users) >= '10'
   ORDER BY t.total_users DESC
Suraj
  • 2,181
  • 2
  • 17
  • 25