开发者

Are 2 queries necessary in group by 2 columns, then group by 1 column?

开发者 https://www.devze.com 2023-04-04 07:29 出处:网络
I have a table with email addresses (colums: id, email, user, date). I\'m trying to sum email addresses by date then user, which I\'m able to do with the below code; but then also sum the total for al

I have a table with email addresses (colums: id, email, user, date). I'm trying to sum email addresses by date then user, which I'm able to do with the below code; but then also sum the total for all users and display it below that date. I'm not sure how to do that... do I nee开发者_运维知识库d to do another query to total for each 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 />";
}

What I have:

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

What I would like:

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

Thanks

EDIT: Here's my code that works:

$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 />";
}


See WITH ROLLUP (a GROUP BY modifier).

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

would give you:

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


I think you can use UNION ALL to do this. It goes something like this:

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

Or you can go in the PHP way:

$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)'];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消