0

I am trying to learn Microsoft SQL Server and I'm trying to figure out how I can do the following.

I have two tables:

users

id  fname   lname   username
111 kely    dike    kdike
222 hana    sho     hsho
333 mike    dime    mdime
444 sergi   xan     sxan

and

email_recipient

id  recipient_id    fname   lname
1      222          hana    sho
2      222          hana    sho
3      222          hana    sho
4      333          mike    dime
5      111          kely    dike
6      111          kely    dike
7      444          sergi   xan
8      444          sergi   xan
9      444          sergi   xan
10     444          sergi   xan

and what I want to do is to count how many emails each user received, something like this:

id  fname   lname  username email_recipient total
111 kely    dike   kdike          2
222 hana    sho    hsho           3
333 mike    dime   mdime          1
444 sergi   xan    sxan           4

Could someone please point in the right direction?

1
  • 2
    Why microsoft sql? How about ANSI SQL? Commented Jan 8, 2013 at 22:01

2 Answers 2

3

You can try this.

SELECT a.id, a.fname, a.lname, a.username, COUNT(*) AS email_recipient_total
FROM users a
INNER JOIN email_recipient b ON b.recipient_id = a.id
GROUP BY a.id, a.fname, a.lname, a.username

Result

|  ID | FNAME | LNAME | USERNAME | EMAIL_RECIPIENT_TOTAL |
----------------------------------------------------------
| 111 |  kely |  dike |    kdike |                     2 |
| 222 |  hana |   sho |     hsho |                     3 |
| 333 |  mike |  dime |    mdime |                     1 |
| 444 | sergi |   xan |     sxan |                     4 |

See it in action

Sign up to request clarification or add additional context in comments.

6 Comments

Why did you ask the question if you knew the answer?
@Bohemian I asked why Microsoft SQL
@njk Do we need to group them by all GROUP BY a.id, a.fname, a.lname, a.username ? I tested your fiddle and it works same for GROUP BY a.id
@sansix The fiddle was tested on a MySQL environment. OP is using MSSQL which is ANSI standard.
@njk so you mean to say "it may produce different result on MSSQL" if one goes with GROUP BY a.id only
|
0

My guess is this might have a slightly better performance, but nonetheless, essentially the same answer:

SELECT 
  a.id, 
  a.fname, 
  a.lname, 
  a.username, 
  b.email_recipient_total
FROM users a
  INNER JOIN (
      select recipient_id, COUNT(*) AS email_recipient_total
      from email_recipient
      group by recipient_id
    ) b ON b.recipient_id = a.id

Comments

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.