需要有关在MySQL中一起使用COUNT和SUM的帮助

时间:2013-04-20 18:48:16

标签: mysql sql database

我有两张桌子:研究所&当然

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)

我真的很感激帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'