简体   繁体   English

如何计算已加入SQL的事件

[英]How do i count occurences that were joined SQL

I am joining two tables: 我要加入两个表:

DECLARE @Temp TABLE (
id INT)

INSERT INTO @Temp
VALUES (5)
,(2)
,(3)

DECLARE @Temp2 TABLE (
member_id INT)

INSERT INTO @Temp2
VALUES (5)
,(1)
,(3)

How do i count the number of rows that can be LEFT joined and the ones that can't. 我如何计算可以左联接和不能左联接的行数。 In this example: 5 & 3 from @Temp can be joined to @Temp2 and only 2 from @Temp can't be joined. 在此示例中:@Temp中的5和3可以与@ Temp2连接,而@Temp中只有2不能连接。 I would like my output to show the following: 我希望我的输出显示以下内容:

+--------+------------+
| Joined | Not_Joined |
+--------+------------+
|      2 |          1 |
+--------+------------+

You can do this in a single query using COUNT and SUM. 您可以使用COUNT和SUM在单个查询中执行此操作。 This should produce the results you are looking for. 这应该产生您想要的结果。

DECLARE @Temp TABLE (
id INT)

INSERT INTO @Temp
VALUES (5)
,(2)
,(3)

DECLARE @Temp2 TABLE (
member_id INT)

INSERT INTO @Temp2
VALUES (5)
,(1)
,(3)

select Joined = count(t2.Member_id)
    , NotJoined = sum(case when t2.Member_id is null then 1 end)
from @Temp t
left join @Temp2 t2 on t2.member_id = t.id

The count from @Temp that EXISTS in @Temp2: @ Temp2中存在的@Temp计数:

SELECT COUNT(*) FROM @TEMP WHERE ID IN(SELECT MEMBER_ID FROM @TEMP2)

The count from @Temp2 not in @Temp: @ Temp2中的计数不在@Temp中:

SELECT COUNT(*) FROM @TEMP2 WHERE MEMBER_ID NOT IN(ID FROM @TEMP)

Now to create a single result set, there are many ways but here is a simple one: 现在要创建一个结果集,有很多方法,但是这里有一个简单的方法:

SELECT 
    (SELECT COUNT(*) FROM @TEMP2 WHERE MEMBER_ID IN(ID FROM @TEMP)) AS [Joined],
    (SELECT COUNT(*) FROM @TEMP WHERE ID NOT IN(SELECT MEMBER_ID FROM @TEMP2)) AS [NotJoined]

@Sean Lange's answer is more specific to the JOIN question, my answer simply counts what exists in the lists. @Sean Lange的答案更特定于JOIN问题,我的答案只是计算列表中存在的内容。

Select count(*) as 'NOT Joined ',
 (Select t1.count(*) from table1 
 t1)-count(*) as 'Joined' 
 from table1 where id NOT IN (Select member_id from table2);

Its basically how a left join works that is Common values of both the tables plus the value of table 1 which doesnt exists in table 2. 它基本上是左联接的工作方式,即两个表的公用值加上表2中不存在的表1的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM