SQL Server查询+加入结果

时间:2013-03-15 18:22:28

标签: sql sql-server

我有这样的查询:

SELECT recipientid AS ID,
COUNT(*) AS Recieved FROM Inbox
GROUP BY recipientid

UNION

SELECT SenderId,
COUNT(*) AS [Sent] FROM Inbox
GROUP BY SenderId

输出:

RecipientID  Recieved

001             3
001             4
002             4
002             2
003            18
003            55

如何重写这样的方式,它显示如下:

RecipientID  Recieved  Sent

001             3       4
002             4       2
003            18       55

感谢。

4 个答案:

答案 0 :(得分:3)

只需加入子查询:

select a.ID,Received,Sent
from(
  SELECT recipientid AS ID,
  COUNT(*) AS Recieved FROM Inbox
  GROUP BY recipientid
)a
full outer join(
  SELECT SenderId as ID,
  COUNT(*) AS [Sent] FROM Inbox
  GROUP BY SenderId
)b
on (a.ID = b.ID)
order by a.ID;

请注意,这会抓取所有收件人或发件人的所有sentreceived值。如果您只想要ID属于收件人和发件人的结果,请执行inner join

答案 1 :(得分:2)

我会在您的查询中添加source列并执行简单的转移

select ID, 
       max (case when source=1 then Cnt else 0 end) as Received,
       max (case when source=2 then Cnt else 0 end) as Sent
from (
  SELECT 1 as Source, 
         recipientid AS ID,
         COUNT(*) AS Cnt 
  FROM Inbox
  GROUP BY recipientid
  UNION
  SELECT 2 as Source, 
         SenderId,
         COUNT(*)  
  FROM Inbox
  GROUP BY SenderId
  ) x
GROUP BY ID

答案 2 :(得分:0)

如果是Postgres,MS SQL或其他支持CTE的人 -

With Both as
(
SELECT
  recipientid AS ID,
  Count(*) AS Recieved,
  0 as [Sent] 
FROM Inbox
GROUP BY recipientid
UNION
SELECT
  SenderId as ID,
  0 as Recieved,
  Count(*) AS [Sent]
FROM Inbox
GROUP BY SenderId
)
SELECT
  ID,
  Sum(Received) as [Received],
  Sum(Sent) as [Sent]
FROM BOTH
GROUP BY ID
ORDER BY 1

答案 3 :(得分:0)

假设您有一个包含ID的users表,您可以执行以下操作:

SELECT
    users.id,
    COUNT(sent.senderid) AS sent,
    COUNT(received.recipientid) AS received
FROM
    users
    LEFT JOIN inbox AS sent ON sent.senderid = users.id
    LEFT JOIN inbox AS received ON received.recipientid = users.id
GROUP BY sent.senderid, received.recipientid
ORDER BY users.id;