2013-03-15 150 views
1

我有這樣的查詢: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 

謝謝。

+1

請指定你是目標的RDBMS通過添加適當的標籤(Oracle,SQL Server,MySQL等)。可能會有利用不被普遍支持的語言或產品功能的答案。此外,通過使用特定的RDBMS標記它,您的問題可能會得到更適合回答的人的關注。 – Taryn 2013-03-15 18:27:19

回答

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

+0

您希望這是一個完整的外連接,而不是內連接,否則您只會收到發送和接收消息的收件人。 – MattW 2013-03-15 18:26:22

+0

@MattW - 好的電話(雖然這個問題並不完全清楚)。 Lemme編輯... – 2013-03-15 18:26:52

+0

ID在第一個選擇行中不明確。 – KekuSemau 2013-03-15 18:27:28

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 
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 
+1

我可能會建議使用'SUM'而不是'MAX'。 – Taryn 2013-03-15 18:28:36

+0

我想過了,這通常是我所做的(SUM而不是MAX),但內部的兩個查詢無論如何都是分組的,所以它是安全的......但它可能更清晰......另外,我甚至不需要內心小組 – alzaimar 2013-03-15 18:29:55

0

假設你有一個users表與ID,你可以做這樣的事情:

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;