mysql - SQL 脚本 需要帮助

标签 mysql sql scripting sql-scripts

我正在处理以下查询,但无法弄清楚一件事。底部主查询的结果如下:-

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

我想将国家/地区的研究所添加为第二列。 表名称 - 国家 主键 - ID

该查询很容易理解。我应该如何继续或将以下查询容纳到大查询中,我可以获得最终结果:-

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 != ''  

//主查询从这里开始

   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

最佳答案

试试这个

   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

关于mysql - SQL 脚本 需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263037/

相关文章:

sql - MS SQL 配置与 Slick 2.0.1 和 Playframework 2.2.2

javascript - 通过 getContext 从 HTML 标记中获取文本 - Google Apps 脚本 - 电子表格

bash - 使用 Bash 确定 URL 是 HTTP 还是 HTTPS

bash - 防止显示键入的字符(例如在 termios 中禁用 "echo"属性)

mysql - 如何提高选择操作的执行速度

mySQL 5.5 - 将值透视到与 UNION 链接的两个表之后的列

html - 如何通过查询去除重复项?

php - 将网站从我的计算机移动到主机或服务器?

javascript - Express js 中的一次性密码生成

mysql - SQL在数据库结构中允许独立表吗?