2

我有 2 张桌子:学院和课程

Institute
---------
i_id       i_name      i_city
------     --------    --------
1          Name 1      London
2          Name 2      Manchester
3          Name 3      London

Course
-------
c_id       i_id        stream
------     -------     --------
1          1           Engineering
2          1           Engineering
3          2           Engineering
4          3           Engineering

现在我正在努力实现三件事:

a) 每个城市提供工程课程的学院数量。b) 提供工程课程的学院总数(不同)。

我开始写下面的查询来实现这一点:

SELECT institute.i_city, 
COUNT( DISTINCT institute.i_id ) AS institute_count_per_city
FROM institute, course
WHERE institute.i_id = course.i_id
AND course.stream =  'Engineering'
GROUP BY institute.i_city

我得到以下结果:

i_city      institute_count_per_city
-------     -------------------------
London      2
Manchester  1

现在我已经达到了每个城市的机构数量。

我不知道如何获得同一查询中的机构总数,在上面的示例中为 3 (2+1)

我非常感谢您的帮助。

4

2 回答 2

3

使用ROLLUP

SELECT institute.i_city, 
COUNT( DISTINCT institute.i_id ) AS institute_count_per_city
FROM institute, course
WHERE institute.i_id = course.i_id
AND course.stream =  'Engineering'
GROUP BY institute.i_city WITH ROLLUP

它将使用SUM您的聚合值添加额外的行。

更新

GrandTotal版本:

SELECT IFNULL(institute.i_city, 'GrandTotal'), 
COUNT( DISTINCT institute.i_id ) AS institute_count_per_city
FROM institute, course
WHERE institute.i_id = course.i_id
AND course.stream =  'Engineering'
GROUP BY institute.i_city WITH ROLLUP
于 2013-04-20T18:50:52.683 回答
1

联合查询有帮助吗?

 your existing query
 union
 select 'total' I_city, count(*) institute_count_per_city
 FROM institute, course
 WHERE institute.i_id = course.i_id
 AND course.stream =  'Engineering'
 GROUP BY 'total'
于 2013-04-20T18:52:09.520 回答