简体   繁体   中英

mysql query that outputs a table of data showing count

I have researched this and have not found the answer, so I thought someone here could shed some light. I'm trying to create a table of data returned showing the number of games picked for each user grouped by week numbers.

Database structure:

id  |  user   |   team    | week_number
----+---------+-----------+-------------
1   |  john   |  eagles   |  1 
2   |  john   |  saints   |  1 
3   |  harry  |  patriots |  1 
4   |  frank  |  cowboys  |  1
5   |  john   |  falcons  |  2
6   |  frank  |  cardinals|  2

Desired output:

week_number | frank | harry | john
------------+-------+-------+-------
     1      |    1  |    1  |   2
     2      |    1  |    0  |   1

I'll be using PHP to display the output.

The alternative to your desired output could be:

WEEK_NUMBER USER    GAMES  
1          frank    1  
1          harry    1  
1          john     2  
2          frank    1  
2          john     1  

If this output could work for you, then you can run the following query:

select week_number,user,count(team) as games from table 
group by week_number,user;

After banging my head in the wall, I got enlightenment and got the query finally. ;)

You could run this to achieve your desired output:

SELECT  T.week_number,
        IFNULL(SUM((CASE WHEN T.user = 'frank' THEN T.games END)),0) frank,
        IFNULL(SUM((CASE WHEN T.user = 'harry' THEN T.games END)),0) harry,
        IFNULL(SUM((CASE WHEN T.user = 'john' THEN T.games END)),0) john
FROM    (select week_number,user,count(team) as games from table_name group by week_number,user) as T
GROUP BY week_number

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM