简体   繁体   English

mysql查询输出显示计数的数据表

[英]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. 我将使用PHP来显示输出。

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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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