I have the following data in my database table, since I'm fairly new to MYSQL i'm having problems in querying it to give me the following output

   City      Subject
   london    english  
   toronto   math     
   london    math     
   london    math     
   toronto   english  
   toronto   english  

There can only be two subjects, english or math. Im trying to output the data this way, first the query should pick all the distinct items in the city column. Then tell me the count of each subject in that city.

output

  city     English  Math
  london   1        2
  toronto  2        1

I tried grouping, but since I don't know mysql that well, I realized it just groups the subjects together and eats the cities while grouping.

有帮助吗?

解决方案

try this:

SELECT city,
  SUM(IF(subject='english',1,0)) AS English,
  SUM(IF(subject='math',1,0)) AS Math
FROM foo
GROUP BY city;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top