2013-07-10 131 views
2

我有2个表具有相同的用户ID,类别,计数模式。我需要一个查询来总结每个用户ID /类别对的计数。有时候一对会存在于一张桌子里,而不是另一张。我在执行连接时遇到了问题,而不会丢失仅在1个表中存在用户ID /类别对的行。这就是我想要(没有成功):SQL连接不丢失行

select a.user, a.category, count=a.count+b.count 
from #temp1 a join #temp2 b 
on a.user = b.user and a.category = b.category 

例子:

输入:

user category count 
id1  catB  3 
id2  catG  9 
id3  catW  17 

user category count 
id1  catB  1 
id2  catM  5 
id3  catW  13 

所需的输出:

user category count 
id1  catB  4 
id2  catG  9 
id2  catM  5 
id3  catW  30 

更新: “计数” 是而不是实际的列名称。为了这个例子我只是用它,我忘了它是一个保留字。

+0

ID2为什么不总结?它在两个表中。 –

+0

@SNash,类别不同。您可能需要重新阅读求和要求。 –

回答

4

您需要:

  1. 使用全外连接,所以你不降在一个表中存在的行,而不是其他
  2. 合并之前,除了计数,因为0 + NULL = NULL

另外,因为COUNT是保留字,所以我会建议转义它。

因此,使用所有这些准则,您的查询就会变成:

SELECT COALESCE(a.user, b.user) AS user, 
     COALESCE(a.category, b.category) AS category, 
     COALESCE(a.[count],0) + COALESCE(b.[count],0) AS [count] 
FROM #temp1 AS a 
FULL OUTER JOIN #temp2 AS b 
      ON a.user = b.user AND 
       a.category = b.category 
+0

完美!我没有意识到COALESCE,这正是我需要的。我也相信“AS [count]”是无关的,因为你在该行的开始处有“[count] =”。 – JCB

+0

@JCB,我的意思是删除'''[count] ='''部分,这是我在上次编辑中完成的。感谢您指出了这一点。 –

1

一个接近这种方式是一个完全外部联接:

select coalesce(a.user, b.user) as user, 
     coalesce(a.category, b.category) as category, 
     coalesce(a.count, 0) + coalesce(b.count, 0) as "count" 
from #temp1 a full outer join 
    #temp2 b 
    on a.user = b.user and 
     a.category = b.category; 

使用full outer join,你必须要因为当只有一个表中的匹配项时,关键字段可以是NULL。因此,select往往有很多coalesce()(或类似的结构)。

另一种方法是使用union all查询与聚合:

select "user", category, SUM(count) as "count" 
from ((select "user", category, "count" 
     from #temp1 
    ) union all 
     (select "user", category, "count" 
     from #temp2 
    ) 
    ) t 
group by "user", category