dongyuanguang3893
dongyuanguang3893
2013-12-13 08:27

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

已采纳

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 donkey111111 8年前

    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.

    点赞 5 评论 复制链接分享