MySQL SUM(),COUNT()和GROUP BY

时间:2014-09-23 03:48:06

标签: mysql sql

我有一个关于MySQL的特殊问题。请查看下面的查询和结果集:

SELECT `SentTo`, 
       `Read`
FROM `Emails` as t

hello@mydomain.com   | 1
--------------------------------
hello@mydomain.com   | 0
--------------------------------
hello@mydomain.com   | 1
--------------------------------
support@mydomain.com | 0
--------------------------------
support@mydomain.com | 1
--------------------------------

我想知道每封电子邮件的电子邮件数量,以及总阅读量。我将通过减去总数并在脚本方面阅读来解读,在这里不需要它。

Email                | Total | Read
--------------------------------------
hello@mydomain.com   |   3   |   1
--------------------------------------
support@mydomain.com |   2   |   1
--------------------------------------

有什么建议吗?我试图对此应用子查询,但我找不到合适的解决方案。

3 个答案:

答案 0 :(得分:3)

这应该可以使用GROUP BY

SELECT `SentTo`,
       COUNT(*) Total,
       SUM(`Read`=0) 
FROM Emails
GROUP BY `SentTo`

答案 1 :(得分:1)

“分组依据”子句可以解决此问题,如下所示:

SELECT `SentTo`, COUNT(*) as totalSend, (totalSend - SUM(`Read`)) as totalUnread
FROM `Emails`  
GROUP BY `SentTo`

答案 2 :(得分:0)

分组应该给出所需的结果

SELECT sentTo,
       Sum(READ) AS TotalRead,
       Sum(CASE WHEN READ =0 THEN 1 ELSE 0) AS Unread
FROM Emails
GROUP BY sentTo