SQL连接基于两个表

时间:2015-06-10 23:35:20

标签: sql sql-server

我想组合两个表,并按count()和按功能分组获取名称的总数#。

表1如下所示;

name       branch       sports             player no
----       -----        ------             --------
Mike        120         basketball           15
David       110         soccer               18  

表2如下所示;

jersey color      player no        height
----------        ---------        ------
Blue               15                182
Green              18                174

我尝试通过内部联接组合两个表,并根据名称计算它们,例如;

SELECT name, branch, sports,
FROM TABLE_1

INNER JOIN TABLE_2 
ON  
TABLE_1.player no = TABLE_2.player no

COUNT(name) AS TOTAL
GROUP BY name, branch, sports, jersey color, player no, height

输出应该是

name       branch       player no      jersey color     height      
----       ------       -------         --------         ----
Mike         120          15             Blue             182
David        110          18             Green            174
Mike         120          15             Blue             182
Mike         120          15             Blue             182
David        110          18             Green            174

计数(姓名)后

name       branch       player no      jersey color     height      Total   
----       ------       -------         --------         ----       -----
Mike         120          15             Blue             182         3
David        110          18             Green            174         2

我一直在思考为什么我无法做到这一点?

1 个答案:

答案 0 :(得分:1)

您实际上是在尝试将结果一个接一个地组合,而不是并排。这需要union [all],而不是join

SELECT   name, COUNT(*)
FROM     (SELECT name FROM table1
          UNION ALL
          SELECT name FROM table2) t
GROUP BY name