具有相同表计数的多个连接

时间:2017-01-05 04:29:32

标签: sql sql-server inner-join sql-server-2016

我有一个类似于下面的表结构:

declare @t1 table (code varchar)
declare @t2 table (id int, code varchar, closed bit)

@ t2保持打开/关闭@ t1中的代码:

insert into @t1 values ('x')

insert into @t2 values (1, 'x', 1)
insert into @t2 values (2, 'x', 1)
insert into @t2 values (3, 'x', 0)

我正在尝试获取代码的打开/关闭计数:

select 
count (t2_open.id) as opencount
, count (t2_closed.id) as closecount
from @t1 t1
inner join @t2 t2_open on t2_open.code = t1.code AND t2_open.closed = 0
inner join @t2 t2_closed on t2_closed.code = t1.code AND t2_closed.closed = 1

返回2& 2,我看不出我在这里做错了什么,为什么不回归1& 2?

不应该从我的查询中选择*返回null并且当记录不匹配时返回正确的计数?我期待select *返回3条记录,但它返回2条记录,其中两行中的id为3。

1 个答案:

答案 0 :(得分:3)

您计算的总记录数不是单个值

SELECT t1.code,
       Count (CASE WHEN t2.closed = 1 THEN 1 END) AS opencount,
       Count (CASE WHEN t2.closed = 0 THEN 1 END) AS closecount
FROM   @t1 t1
       LEFT JOIN @t2 t2
              ON t2.code = t1.code
GROUP  BY t1.code 

更新:

让我们分解联接

SELECT t1.code,t2_open.closed
FROM   @t1 t1
       INNER JOIN @t2 t2_open
               ON t2_open.code = t1.code
                  AND t2_open.closed = 0 

在第一次加入时,您将拉出关闭= 0的记录,因此结果将类似于

+------+--------+
| code | closed |
+------+--------+
| x    |      0 |
+------+--------+

现在,在上述结果的基础上,您将使用代码加入@ t2并关闭= 1

SELECT t1.code,t2_open.closed,t2_closed.closed
FROM   @t1 t1
       INNER JOIN @t2 t2_open
               ON t2_open.code = t1.code
                  AND t2_open.closed = 0
       INNER JOIN @t2 t2_closed
               ON t2_closed.code = t1.code
                  AND t2_closed.closed = 1 

我们有两个关闭= 1的记录,对于相同的代码,当我们加入前一个结果时,关闭也将重复两次,因为两个关闭= 1

+------+--------+--------+
| code | closed | closed |
+------+--------+--------+
| x    |      0 |      1 |
| x    |      0 |      1 |
+------+--------+--------+

正如你所看到的,我们在加入后有两个关闭= 0,所以在计算时你会看到两个接近计数

相关问题