0

我有两个表registeredand attended,每个表有两列:AttendentIdand SessionId。我想分别AttendantId从这两个表中查询特定会话 ID 的计数。

例子:

挂号的

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
4

5 回答 5

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);

请参阅带有演示的 SQL Fiddle

于 2013-05-13T15:14:37.920 回答
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

SQLFiddle

于 2013-05-13T15:10:59.467 回答
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
于 2013-05-13T15:15:19.897 回答
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

SQL 小提琴

| SESSIONID | COLUMN_1 | COLUMN_2 |
-----------------------------------
|       SN1 |        2 |        1 |
|       SN2 |        1 |        0 |
|       SN3 |        1 |        1 |

希望这可以帮助....

于 2013-05-13T15:22:48.800 回答
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 
于 2013-05-13T15:26:19.890 回答