[英]SQL Server query + joining results
我有這樣的查詢:
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
謝謝。
只需加入子查詢:
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
獲取所有收件人或發件人的所有已sent
和已received
值。 如果您只想要ID
屬於接收者和發送者的結果,請執行一個inner join
。
我將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
如果是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
假設您有一個包含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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.