在php中类似的2个字段分组?

时间:2013-01-09 07:27:08

标签: php mysql group-by

如何在php中分组两个相似的字段?

我尝试了GROUP BY DATE(bill.date),bill.agent_id,但它不适用于我

表结构1:http://i.stack.imgur.com/yvBF0.jpg(表名为bill_agents) 表结构2:http://i.stack.imgur.com/38tKh.jpg(表名是账单)

当前结果

+---------+----+----+----+-----+----+
|         |  1 |  2 |  3 |   4 |  5 |
+---------+----+----+----+-----+----+
| Agent 1 | 35 |  0 |  0 |   0 |  0 |
| Agent 2 |  0 | 10 |  0 |   0 |  0 |
| Agent 1 |  0 |  0 | 12 |   0 |  0 |
| Agent 3 |  0 |  0 |  0 | 100 |  0 |
| Agent 6 |  0 |  0 |  0 |   9 |  0 |
| Agent 2 |  0 |  0 |  0 |   9 | 14 |
+---------+----+----+----+-----+----+

But I want To get Like The Following

+---------+----+----+----+-----+----+
|         |  1 |  2 |  3 |   4 |  5 |
+---------+----+----+----+-----+----+
| Agent 1 | 35 |  0 | 12 |   0 |  0 |
| Agent 2 |  0 | 10 |  0 |   0 | 14 |
| Agent 3 |  0 |  0 |  0 | 100 |  0 |
| Agent 6 |  0 |  0 |  0 |   9 |  0 |
+---------+----+----+----+-----+----+

Php Code粘贴在我正在使用的下方。

<table width="100%" border="1" cellspacing="4" cellpadding="1">
  <tr>
    <td>&nbsp;</td>
     <?php
for ($i=01; $i<=31; $i++)
  {?>
    <td><?php echo $i; ?></td>
    <?php

  }
?>
    <td>Total</td>
  </tr>
  <?php 

    $query4 = "SELECT bill.agent_id, bill.date, SUM(bill.amount + bill.cheque) AS total, bill_agents.id,bill_agents.name ".
          "FROM bill, bill_agents ".
          "WHERE bill.agent_id = bill_agents.id AND YEAR(date)  = YEAR(CURDATE()) AND MONTH(date) = MONTH(CURDATE()) ". 
          "GROUP BY bill.agent_id , DATE(bill.date)   ".

              // "GROUP BY bill.agent_id , DATE(bill.date)  ".
              "ORDER BY bill.date ASC";

    $result4 = mysql_query($query4) or die('Error, query failed1'); 
    if  (mysql_num_rows($result4)>0){
    mysql_data_seek($result4, 0);   

?>
  <?php $total_1 = 0;  while($row4 = mysql_fetch_array($result4, MYSQL_ASSOC)){?>
  <?php $date =    $row4['date'];

    $var = $date;
    $date = date("d-m-Y", strtotime($var) );
    $date=substr($date, 0, -8); 

    echo $date;

    ?>
  <tr>
    <td><?php echo $row4['name']; ?></td>
    <?php
for ($i=01; $i<=31; $i++)
  {?>
    <td><?php if ($date == $i) echo $row4['total']; ?></td>
    <?php

  }
?>
    <td></td>
  </tr>
  <?php } } ?>
  <tr>
    <td colspan="31"></td>
    <td>Total</td>
    <td></td>
  </tr>
</table>

1 个答案:

答案 0 :(得分:0)

我的理解是,您需要一个代理商处理的总金额以及一年中的特定月份。 然后按如下所示更改您的查询,

<?php
$query = "SELECT b.date,b.agent_id,(SUM(b.amount) + SUM(b.cheque)) AS total,ba.id,ba.name 
FROM bill_agent ba LEFT JOIN bill b ON b.agent_id = ba.id
WHERE YEAR(b.date)  = YEAR(CURDATE()) AND MONTH(b.date) = MONTH(CURDATE())
GROUP BY b.date";

?>