0

I have a particular question which is about MySQL. Please have a look at the query and the result set below:

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

[email protected]   | 1
--------------------------------
[email protected]   | 0
--------------------------------
[email protected]   | 1
--------------------------------
[email protected] | 0
--------------------------------
[email protected] | 1
--------------------------------

I'd like to get the count of the emails for each email, and the total Read. I will get unread by subtracting total and read on the script side, don't really need it here.

Email                | Total | Read
--------------------------------------
[email protected]   |   3   |   1
--------------------------------------
[email protected] |   2   |   1
--------------------------------------

Any advice? I have tried to apply sub-queries to this but I couldn't find a proper solution.

3 Answers 3

4

This should work using GROUP BY:

SELECT `SentTo`,
       COUNT(*) Total,
       SUM(`Read`=0) 
FROM Emails
GROUP BY `SentTo`
Sign up to request clarification or add additional context in comments.

1 Comment

SUM(Read=0) A true Mysql solution for conditional count +1
1

A 'Group by' clause can solve this problem as follows:

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

1 Comment

Besides the fact this isn't valid syntax, it doesn't produce the correct results if it were... First, You can't reference a column alias in the SELECT query like this. Second, COUNT(DISTINCT SentTo) will always equal 1 -- OP is asking for COUNT(*)...
0

Group by should give the desired result

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

3 Comments

This would SUM the Read column, not SUM when it's equal to 0. Also, Read is a reserved word in MySql and would need to be escaped.
OP wants values when read is 1, as you can see in the example where first email got 3 reads
That's the Total, which is the COUNT(*). For example, hello has 3 total records, but only 1 with read=0. This query returns hello with 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.