2013-04-20 148 views
2

我有2個表使用COUNT和SUM在一起:研究所&課程需要幫助的在MySQL

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)

我會很感激的幫助。

回答

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這將給你一個額外的行'城市'null和提供工程ocurse的機構的總數。 – Andomar 2013-04-20 18:52:07

+0

非常感謝。太棒了!我可以用其他類似GrandTotal替換null嗎? – 2013-04-20 19:45:22

+0

我已經更新了我的答案。 – MarcinJuraszek 2013-04-20 19:46:53

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' 
+0

非常感謝。 – 2013-04-20 21:23:50