是否需要先按 2 列分组,再按 1 列分组进行 2 次查询?
我有一个包含电子邮件地址的表(列:id、电子邮件、用户、日期)。我正在尝试按日期和用户对电子邮件地址进行求和,我可以使用下面的代码来完成此操作;但随后还要对所有用户的总数进行求和并将其显示在该日期下方。我不知道该怎么做...我需要再做一次查询来计算每个日期的总计吗?
$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 />";
}
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 need 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 />";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅
使用 ROLLUP
(GROUP BY
修饰符)。会给你:
See
WITH ROLLUP
(aGROUP BY
modifier).would give you:
我认为你可以使用 UNION ALL 来做到这一点。它是这样的:
或者你可以用 PHP 方式:
I think you can use UNION ALL to do this. It goes something like this:
Or you can go in the PHP way: