2

如果我有这个 SQL 查询:

select substring(id for 2) as key, 
yw, count(*)
from pref_money group by yw, key

每周和每个键返回的用户数:

 key |   yw    | count
-----+---------+-------
 VK  | 2010-45 |   144
 VK  | 2010-44 |    79
 MR  | 2010-46 |    72
 OK  | 2010-48 |   415
 FB  | 2010-45 |    11
 FB  | 2010-44 |     8
 MR  | 2010-47 |    55
 VK  | 2010-47 |   136
 DE  | 2010-48 |    35
 VK  | 2010-46 |   124
 MR  | 2010-44 |    40
 MR  | 2010-45 |    58
 FB  | 2010-47 |    13
 FB  | 2010-46 |    13
 OK  | 2010-47 |  1834
 MR  | 2010-48 |    13
 OK  | 2010-46 |  1787
 DE  | 2010-44 |    83
 DE  | 2010-45 |   128
 FB  | 2010-48 |     4
 OK  | 2010-44 |  1099
 OK  | 2010-45 |  1684
 DE  | 2010-46 |   118
 VK  | 2010-48 |    29
 DE  | 2010-47 |   148

那么我该如何计算这些用户呢?我正在努力:

    $sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
                         from pref_money group by yw, key');
    $sth->execute();
    while ($row = $sth->fetch(PDO::FETCH_ASSOC))
            ++$users[$row['yw']][$row['key']];
    print_r($users);

但得到许多错误。

我正在尝试获取堆积条形图的数据。x 轴将显示周数,y 轴将显示用户数,按键字符串分组。

谢谢!亚历克斯

4

2 回答 2

2

您是要总计count列还是仅获取返回的行数?如果是后者,php 有一个方法。如果是前者,则需要$users[$row['yw']][$row['key'] += $row['count']改为(假设已经创建了数组)。

于 2010-11-29T14:28:54.770 回答
-1
$sth = $db->prepare('select substring(id for 2) as key, yw, count(*)
                         from pref_money group by yw, key');
    $sth->execute();
    $users=array();  //  register $users as an array.
    while ($row = $sth->fetch(PDO::FETCH_ASSOC))
            if(!isset($users[$row['yw']])){// see if $users['whatever_key'] has already been set
               $users[$row['yw']]=0;//if not, initialize it as a default starting value of 0
             }
            $users[$row['yw']]+=$row['key'];//now we won't get any nasty notices here about undeclared variables or keys..
    print_r($users);
于 2010-11-29T14:26:57.030 回答