dongyuanguang3893 2013-12-13 08:27
浏览 89
已采纳

为另一列中的每个值获取一列中的相似值的总和

ok, I have a mysql table named "sales_records" like so:

  User    saleType
+-------+-------+------+
| Jeff  | Sale_Closed  |
+-------+-------+------+
| Jeff  | Sale_null    |
+-------+-------+------+
| Sean  | sale_closed  |
+-------+-------+------+
| Jeff  | sale_closed  |
+-------+-------+------+
| Sean  | sale_closed  |
+-------+-------+------+
| Mark  | Sale_null    |
+-------+-------+------+
| Mark  | sale_closed  |
+-------+-------+------+
| Josh  | sale_closed  |
+-------+-------+------+
| Josh  | sale_closed  |
+-------+-------+------+

I'm trying to count up each saleType for each User.. In other words.. Jeff has 2 "sale_closed" and 1 "sale_null. Mark has 1 "sale_closed" and 1 "sale_null", and so on..

and store it into an array.. (Json) like so.:

{"jeff":{"sale_closed":2,"sale_null":1},"sean":{"sale_closed":2},"Mark":{"sale_closed":1, "sale_null":1},"Josh":{"sale_closed":2}

Ok, so here's my attempt:

<?php
// assuming database connection has already been established..

$result = mysql_query("SELECT DISTINCT `USER' FROM `sales_records`");
while($row = mysql_fetch_assoc($result)) {
    $user_array[] = $row['User']; 
}

foreach ($user_array as $user) {
    $json_array[$user] = mysql_query("SELECT saleType FROM sales_records WHERE user='$user'");

    while ($row = mysql_fetch_array($json_array[$user])) { // AND HERE IS WHERE i GET STUCK!!!
        $json_array[$user][$username][] = $row['saleType']; // I DON'T KNOW WHERE TO GO FROM HERE...
    }
} // AM I APPROACHING THIS CORRECTLY?..

//...
// Once I have all the 'saleType's for each user, maybe I could use:
array_count_values()... or something.

?>
  • 写回答

1条回答 默认 最新

  • donkey111111 2013-12-13 08:33
    关注

    You can get all the data you need in a single query:

    SELECT user, saleType, count(*) totalSales FROM sales_record
    GROUP BY user, saleType
    

    That will return all the results in 3 columns that should be easy to turn into JSon.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?