内连接2计数语句

时间:2013-12-30 22:26:38

标签: mysql sql

我在加入两个计数语句时遇到了麻烦,最让我失望的是团队成员不同

SELECT COUNT(teamid) AS homescore FROM goals WHERE teamid = 1 AND gameid = 1
SELECT COUNT(teamid) AS awayscore FROM goals WHERE teamid = 2 AND gameid = 1

查询1结果

homescore
    0

查询2结果

awayscore
    0

我想要实现的目标

homescore | awayscore
    0     |     0

3 个答案:

答案 0 :(得分:3)

不确定你想要做什么,但也许这个:

SELECT COUNT(teamid) AS homescore FROM goals WHERE teamid = 1 AND gameid = 1
union
SELECT COUNT(teamid) AS awayscore FROM goals WHERE teamid = 2 AND gameid = 1

编辑:恢复列并处理空值。

select  nvl((SELECT COUNT(teamid) AS score FROM goals WHERE teamid = 1 AND gameid = 1),0) as homescore,
        nvl((SELECT COUNT(teamid) AS score FROM goals WHERE teamid = 2 AND gameid = 1),0) as awayscore
from dual

答案 1 :(得分:2)

我认为这就是你要找的东西。

select 
sum(case when teamid = 1 then 1 else 0 end) as homescore,
sum(case when teamid = 2 then 1 else 0 end) as awayscore
from goals where gameid = 1

答案 2 :(得分:0)

您应该使用内部联接或联合

SELECT COUNT(teamid)AS homescore FROM goals WHERE teamid = 1 AND gameid = 1 UNION SELECT COUNT(teamid)AS awayscore FROM goals WHERE teamid = 2 AND gameid = 1