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?

4

2 回答 2

3

你可以试试这个。

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

结果

| 身份证 | FNAME | 名称 | 用户名 | EMAIL_RECIPIENT_TOTAL |
-------------------------------------------------- --------
| 111 | 凯利 | 堤防| 克迪克 | 2 |
| 222 | 花 | 笑| 萧 | 3 |
| 333 | 迈克 | 一角钱 | mdime | 1 |
| 第444章 塞尔吉 | 珊 | sxan | 4 |

看到它在行动

于 2013-01-08T22:04:41.073 回答
0

我的猜测是这可能会有更好的性能,但无论如何,基本上是相同的答案:

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
于 2013-01-08T22:42:49.030 回答