1

次のようなクエリがあります。

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

4 に答える 4

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;

これにより、受信者または送信者のすべての値sentと値が取得されることに注意してください。受信者と送信者に属するのreceived結果のみが必要な場合は、を実行します。IDinner join

于 2013-03-15T18:25:24.873 に答える
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
于 2013-03-15T18:27:19.647 に答える
0

CTEをサポートしているのがPostgres、MS SQL、またはその他の場合-

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
于 2013-03-15T18:26:25.507 に答える
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;
于 2013-03-15T18:44:11.473 に答える