在SQL查询中显示零值数据?

时间:2009-05-14 12:48:06

标签: sql select count

我有以下两个表(针对此问题进行了简化):

CREATE TABLE team (
 teamID CHAR(6) NOT NULL PRIMARY KEY); 

CREATE TABLE member (
 memberID CHAR(7) NOT NULL PRIMARY KEY,
 teamID CHAR(6) NOT NULL REFERENCES team(teamID) );

我还有以下查询,即列出每个团队中的成员数量:

SELECT teamID, count(memberID) AS [noOfMembers]
FROM member
GROUP by teamID;

但是,我有四支队伍(MRT1,MRT2,MRT3和MRT4)。我的表中的成员只属于第2组和第3组,因此当我运行查询时,我得到以下输出:

MRT2:7, MRT3:14

我不确定如何调整查询以列出所有4支球队:

MRT1:0, MRT2:7, MRT3:14, MRT4:0

我一直在搞乱子查询来解决这个问题而没有任何运气。有任何想法吗?感谢

4 个答案:

答案 0 :(得分:5)

尝试从TEAM中选择离开JOIN-ing会员

SELECT Team.Teamid, count(memberid)
FROM 
    TEAM
LEFT OUTER JOIN 
     Member on Member.teamid = Team.Teamid
GROUP by Team.Teamid

只是为了给你一些背景知识。

它说

  

给我团队中的所有队友,然后为每个队友计算队员表中的比赛,即使没有比赛。

如果您使用

SELECT Team.Teamid, count(memberid)
FROM 
    TEAM
INNER JOIN 
     Member on Member.teamid = Team.Teamid
GROUP by Team.Teamid

这转化为

  

向我提供团队中的所有团队成员,然后为每个团队成员计算成员表中的匹配项,但仅限于匹配项。

答案 1 :(得分:3)

SELECT teamID, count(memberID) AS [noOfMembers]
FROM team
LEFT JOIN member
ON team.teamID = member.teamID
GROUP by teamID;

答案 2 :(得分:2)

我做了这个测试,并为我工作

CREATE TABLE team (
 teamID CHAR(6) NOT NULL PRIMARY KEY); 

CREATE TABLE member (
 memberID CHAR(7) NOT NULL PRIMARY KEY,
 teamID CHAR(6) NOT NULL REFERENCES team(teamID) );

INSERT INTO team (teamID) VALUES ('T1')
INSERT INTO team (teamID) VALUES ('T2')
INSERT INTO team (teamID) VALUES ('T3')
INSERT INTO team (teamID) VALUES ('T4')

INSERT INTO member (memberID, teamID) VALUES ('M1', 'T1')
INSERT INTO member (memberID, teamID) VALUES ('M2', 'T1')
INSERT INTO member (memberID, teamID) VALUES ('M3', 'T1')
INSERT INTO member (memberID, teamID) VALUES ('M4', 'T3')

SELECT Team.teamID, count(member.memberID) AS [noOfMembers]
FROM Team LEFT JOIN member ON Member.teamID = Team.teamID
GROUP BY ALL Team.teamID;

答案 3 :(得分:0)

正确加入TEAM表应解决问题。