简体   繁体   中英

SQL Server query + joining results

I have a query like this:

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

UNION

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

The output:

RecipientID  Recieved

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

How can I rewrite is such a way that it displays like this:

RecipientID  Recieved  Sent

001             3       4
002             4       2
003            18       55

Thanks.

Just join the subqueries:

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;

Note that this grabs all of the sent and received values for any recipients or senders. If you only want results for ID s belonging to recipients and senders, then do an inner join .

I would add a source column to your query and do a simple pivot

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

If it's Postgres, MS SQL or others that support CTEs -

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

Assuming you have a users table with the IDs, you could do something like:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM