我有两个表registered
和attended
,每个表都有两列:AttendentId
和SessionId
。我想从这两个表中分别查询特定会话ID的AttendantId
计数。
示例:
AttendantId SessionId
ID1 SN1
ID2 SN2
ID3 SN1
ID4 SN3
AttendantId SessionId
ID1 SN1
ID4 SN3
我想获得以下输出:
Count(Registered) Count(Attended) Session ID
2 1 SN1
1 0 SN2
1 1 SN3
答案 0 :(得分:3)
您可以使用FULL OUTER JOIN
:
select
coalesce(a.sessionid, r.sessionid) sessionid,
count(r.AttendantId) countRegistered,
count(a.AttendantId) countAttended
from registered r
full outer join attended a
on r.sessionid = a.sessionid
and r.AttendantId = a.AttendantId
group by coalesce(a.sessionid, r.sessionid);
答案 1 :(得分:1)
SELECT
ISNULL(ACount, 0),
ISNULL(RCount, 0),
X.SessionId
FROM
(
SELECT SessionId FROM Registered
UNION -- implies DISTINCT
SELECT SessionId FROM Attended
) X
LEFT JOIN
(SELECT COUNT(*) AS RCount, SessionId
FROM Registered
GROUP BY SessionId) R ON X.SessionId = R.SessionId
LEFT JOIN
(SELECT COUNT(*) AS ACount, SessionId
FROM Attended
GROUP BY SessionId) A ON X.SessionId = A.SessionId
答案 2 :(得分:1)
尝试:
select count(distinct registered),
count(distinct attended),
SessionId
from (select AttendantId registered, null attended, SessionId
from registered
union all
select null registered, AttendantId attended, SessionId
from Attended) sq
group by SessionId
答案 3 :(得分:0)
尝试此查询
select
a.sessionId,
case when aCnt is null then 0 else acnt end,
case when bCnt is null then 0 else bcnt end
from
(select
sessionId,
count(*) aCNt
from
tbl1
group by
sessionid) a
full join
(select
sessionId,
count(*) bCnt
from
tbl2
group by
sessionid) b
on
a.sessionId = b.sessionid
| SESSIONID | COLUMN_1 | COLUMN_2 |
-----------------------------------
| SN1 | 2 | 1 |
| SN2 | 1 | 0 |
| SN3 | 1 | 1 |
希望这会有所帮助......
答案 4 :(得分:0)
假设所有会话ID都存在于已注册的表中
SELECT Sum(CASE
WHEN a.attendentid IS NOT NULL THEN 1
ELSE 0
end) AS Count(registered),
Sum(CASE
WHEN b.attendentid IS NOT NULL THEN 1
ELSE 0
end) AS Count(attended),
a.sessionid
FROM registered a
INNER JOIN attended b
ON a.sessionid = b.sessionid
GROUP BY a.sessionid