使用SQL对列中的项进行计数
我正在尝试编写一个SQL查询,该查询将添加电子邮件地址在Transactions表的sender列和recipient列中的次数 所以 请求输出:使用SQL对列中的项进行计数,sql,sql-server,count,totals,Sql,Sql Server,Count,Totals,我正在尝试编写一个SQL查询,该查询将添加电子邮件地址在Transactions表的sender列和recipient列中的次数 所以 请求输出: Email address | Sent | Received xyz.com 3 1 sdz.com 1 0 abc.com 0 2 bac.com 0 1 到目前为止,我所拥有的
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
谢谢你的帮助 您可以使用
全部联合
和聚合
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
你可以用一笔钱来证明,当你和工会都收到邮件的时候
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
由于您正在进行两个不同的分组,我建议您自行加入,如:
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
如果要使用表提示,则不推荐省略with关键字。当然,NOLOCK暗示了一个许多人并不完全理解的滑坡。
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