组中是否需要2个查询2列,然后按1列分组?

时间:2011-09-11 19:50:10

标签: php mysql count group-by while-loop

我有一个包含电子邮件地址的表格(colums:id,email,user,date)。我试图按日期和用户对电子邮件地址求和,我可以使用下面的代码;但随后也将所有用户的总和相加并在该日期下方显示。我不知道该怎么做...我是否需要对每个日期进行另一次总计查询?

$sql = mysql_query("SELECT date, COUNT(email), user FROM emails GROUP BY DATE(date), user");
while ($row = mysql_fetch_array($sql)){
  echo date('m/d', strtotime($row['date'])) . " " . $row['user'] . " " . $row['COUNT(email)'] . "<br />";
}

我有什么:

date user count(email)
09/09 29 8
09/09 49 9
09/10 29 4
09/10 49 13
09/11 29 1
09/11 49 3

我想要的是什么:

date user count(email)
09/09 29 8
09/09 49 9
09/09 total 17

09/10 29 5
09/10 49 13
09/10 total 18

09/11 29 1
09/11 49 3
09/11 total 4

由于

编辑:这是我的代码:

$sql = mysql_query("SELECT date, COUNT(email), user FROM emails GROUP BY DATE(date), user WITH ROLLUP");

while ($row = mysql_fetch_array($sql)){
  echo date('m/d', strtotime($row['date'])) . " " . (!isset($row['user']) ? 'total' : $row['user']) . " " . $row['COUNT(email)'] . "<br />";
}

2 个答案:

答案 0 :(得分:4)

请参阅 WITH ROLLUP GROUP BY修饰符)。

SELECT DATE(`date`) AS date
     , user 
     , COUNT(email) AS cnt
FROM emails 
GROUP BY DATE(`date`)
       , user 
WITH ROLLUP 

会给你:

date    user   cnt
09/09   29       8
09/09   49       9
09/09   NULL    17

09/10   29       5
09/10   49      13
09/10   NULL    18 

09/11   29       1
09/11   49       3
09/11   NULL     4

NULL    NULL    39

答案 1 :(得分:1)

我认为你可以使用UNION ALL来做到这一点。它是这样的:

SELECT date, COUNT(email), user
FROM emails
GROUP BY DATE(date), user
UNION ALL
SELECT date, COUNT(email), -1
FROM emails
GROUP BY DATE(date)
ORDER date ASC

或者您可以使用PHP方式:

$previousDate = null;
$total = 0;
$sql = mysql_query("SELECT date, COUNT(email), user FROM emails GROUP BY DATE(date), user");
while ($row = mysql_fetch_array($sql)){
    if ($previousDate != date('m/d', strtotime($row['date']))) {
        echo $previousDate . " total " . $total . "<br /><br />";
        $total = 0;
        $previousDate = date('m/d', strtotime($row['date']));
    }

    echo date('m/d', strtotime($row['date'])) . " " . $row['user'] . " " . $row['COUNT(email)'] . "<br />";
    $total = $total + $row['COUNT(email)'];
}