Imagine a table that looks like
| sender_ID
| Receiver_ID
| message_ID
| , say table name is **tb**
now I want to write an SQL query that gives me :
user_id
, Total messages exchanged by that user
. So basically if id = 12 sent 3 messages and received 5 messages, the result will be: 12, 8
I’m not sure if
Select COUNT(MESSAGE_ID)
from tb
group by sender_id, reciever_id
but this is clearly wrong
2
Answers
Use
UNION
to synthesize a table of all the senders and receivers in one column. Then you can join that withtb
to count both IDs.This version, also using a CTE to create a single column of users_ids, has just two table scans.