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

时间:2014-09-13 07:51:31

标签: php mysql sql

我研究了这个并且没有找到答案,所以我认为这里有人可以解释一下。我试图创建一个返回的数据表,显示按周数分组的每个用户的游戏数量。

数据库结构:

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

所需的输出:

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

我将使用PHP来显示输出。

2 个答案:

答案 0 :(得分:1)

您所需输出的替代方法可能是:

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

如果此输出可以为您工作,那么您可以运行以下查询:

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

答案 1 :(得分:0)

在我的头撞墙后,我得到启发并最终得到了询问。 ;)

你可以运行它来实现你想要的输出:

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