2012-09-06 119 views
0

我有一個簡單的查詢:摘要信息欄

SELECT sds.district_id,detail.year, detail.race, SUM(count) 
FROM school_data_race_ethnicity_raw as detail 
INNER JOIN school_data_schools as sds USING (school_id) 
GROUP BY district_id, year, race 

示例結果集:

| 68080104 | 2009 | Multiracial  |   0 | 
| 68080104 | 2009 | White   |  847 | 
| 68080104 | 2010 | American Indian |   1 | 
| 68080104 | 2010 | Asian   |   4 | 
| 68080104 | 2010 | Black   |   17 | 
| 68080104 | 2010 | Hispanic  |   4 | 
| 68080104 | 2010 | Multiracial  |   2 | 
| 68080104 | 2010 | White   |  823 | 
| 68080104 | 2011 | American Indian |   4 | 
| 68080104 | 2011 | Asian   |   4 | 
| 68080104 | 2011 | Black   |   9 | 
| 68080104 | 2011 | Hispanic  |   10 | 
| 68080104 | 2011 | Multiracial  |   24 | 
| 68080104 | 2011 | White   |  767 | 
+-------------+------+-----------------+------------+ 

我想添加一個名爲總第5列,顯示總人口的總和對於給定的年份和地區。例如,如果我2011年在68080104區,總數將是(4 + 4 + 9 + 10 + 24 + 767)。我需要這個作爲這個查詢中的另一列。它也需要快速。 (在10秒以內)。我正在努力如何做到這一點,而不是妥協的速度和數據。

+0

檢查下面我的解決方案,你需要創建一個單獨的查詢來計數值,然後加入它與原來的一個 –

回答

2

使用您需要爲創建一個單獨的查詢,並與原來的加入。試試這個,

SELECT a.*, b.totalCount 
FROM 
    (
     SELECT sds.district_id,detail.year, detail.race, SUM(count) 
     FROM school_data_race_ethnicity_raw as detail 
        INNER JOIN school_data_schools as sds 
         USING (school_id) 
     GROUP BY district_id, year, race 
    ) a INNER JOIN 
    (
     SELECT sds.district_id,detail.year, SUM(count) totalCount 
     FROM school_data_race_ethnicity_raw as detail 
        INNER JOIN school_data_schools as sds 
         USING (school_id) 
     GROUP BY district_id, year 
    ) b ON a.district_id = b.district_id AND 
      a.year = b.year 
1

WITH ROLLUP

SELECT sds.district_id,detail.year, detail.race, SUM(count) 
FROM school_data_race_ethnicity_raw as detail 
INNER JOIN school_data_schools as sds USING (school_id) 
GROUP BY district_id, year, race WITH ROLLUP 
+0

我不想有空值,有沒有辦法做到這一點,而不使用匯總? –

0

在MySQL中,得到在同一行,你幾乎是數據已經做到這一點的加入:

select t.*, t2.cnt as TotalDistrictYear 
from (SELECT sds.district_id,detail.year, detail.race, SUM(count) as cnt 
     FROM school_data_race_ethnicity_raw as detail INNER JOIN 
      school_data_schools as sds USING (school_id) 
     GROUP BY district_id, year, race 
    ) t join 
    (SELECT sds.district_id,detail.year,SUM(count) as cnt 
     FROM school_data_race_ethnicity_raw as detail INNER JOIN 
      school_data_schools as sds USING (school_id) 
     GROUP BY district_id, year 
    ) t2 
    on t.district_id = t2.district_id and 
     t.year = t2.year