I have a sample table in MySQL like this:(The actual table has much more races and schools)
**race** | **school** | **name**
White | MIT | Jack
White | MIT | Li
White | MIT | Don
White | Fordham | Dan
White | Fordham | Nan
White | NYU | Kate
Hispanic | MIT | Jacob
Hispanic | Fordham | Joe
Hispanic | Fordham | Connie
Hispanic | NYU | Sarah
Asian | MIT | Macro
Asian | MIT | Denise
Asian | MIT | Dennie
Asian | MIT | Sasa
Asian | Fordham | Mei
Asian | Fordham | Tian
Asian | Fordham | John
Asian | Fordham | Lala
Asian | NYU | Zed
Asian | NYU | Ann
Asian | NYU | Nancy
AmeIndian| MIT | David
AmeIndian| NYU | Lonnie
Firstly, I will aggregate the number of each race and order them descending. The query looks like this: (I know what to do for this part)
**race** | **Number**
Asian | 11
White | 6
Hispanic | 4
AmeIndian | 2
Finally, I want to get a crosstab query like this: (Just extract the top 3 in term of number of people in each race. Besides, the final query is ordered by the total number of people in each race)
**race** | **MIT** | **Fordham** | **NYU** | **SUM**
Asian | 4 | 4 | 3 | 11
White | 3 | 2 | 1 | 6
Hispanic | 1 | 2 | 1 | 4
I tried the code listed below. I cannot get the "SUM" column. And the number of people in each race under "MIT" and "Fordham" is the same and has duplicates.(refer to need to return two sets of data with two different where clauses) I think it is because I want to order by the total number of people in each race, and order by the total number. However, the order of number of people of each race is different among different schools.
SELECT race,
COUNT(IF(school="MIT",race,0)) as MIT,
COUNT(IF(school="Fordham",race,0)) as Fordham
FROM table_name
GROUP by race