使用SQL计算列中的项目

时间:2017-06-30 15:22:12

标签: sql sql-server count totals

我正在尝试编写一个SQL查询,该查询将添加电子邮件地址在“事务”表中的发件人列和收件人列中的次数。

SO ..

Sender     |  Receipient
xyz.com    |  abc.com
xyz.com    |  xyz.com
sdz.com    |  abc.com
xyz.com    |  bac.com

请求输出:

Email address  |  Sent  |  Received
xyz.com           3           1
sdz.com           1           0
abc.com           0           2
bac.com           0           1

到目前为止我所拥有的:

SELECT Sender, COUNT(Sender) as 'Total Sent', COUNT(recipient) as 'Total 
Received'
FROM Transactions (NOLOCK)
group by Sender
order by sender

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

由于您正在制作2个不同的分组,我建议您自行加入,例如:

SELECT a.Sender, COUNT(a.Sender) AS 'Total Sent',  b.recieved AS 'Total 
Received'
FROM Transactions
JOIN (SELECT Receipient, COUNT(Receipient) AS recieved 
      FROM Transactions
      GROUP BY b.Receipient) b ON b.Receipient=a.Sender
GROUP BY a.Sender

答案 1 :(得分:0)

您可以使用union all和聚合。

select email_address
,count(case when type='Sent' then 1 end) as sent
,count(case when type='Received' then 1 end) as received
from (SELECT Sender as email_address,'Sent' as type
      FROM Transactions 
      UNION ALL
      SELECT Receiver,'Received'
      FROM Transactions 
     ) t
group by email_address

答案 2 :(得分:0)

你可以在案件时使用和,并且联合所有人获取电子邮件

    select Email_address 
        , sum(case when  t_type = 'Sender', then 1 else 0 end) sent
        , sum(case when  t_type = 'Receipient', then 1 else 0 end) Receipient
    from (
        select 'Sender' t_type,   Sender as sent
        from Transactions
        union All
        select 'Receipient' t_type,  Recipient
        from Transactions ) t
    group by Email_address