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

特定の年と地区の総人口の合計を表示する、total という 5 番目の列を追加します。たとえば、私が 2011 年に地区 68080104 にいた場合、合計は (4+4+9+10+24+767) になります。このクエリの別の列としてこれが必要です。また、高速である必要があります。(10 秒未満)。これを行う方法と、速度とデータを妥協しない方法に苦労しています。

4

3 に答える 3

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
于 2012-09-06T15:11:32.577 に答える
1

ロールアップで使用

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
于 2012-09-06T15:07:51.253 に答える
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
于 2012-09-06T15:12:14.517 に答える