如何在连接后列出不同的列并计数?

时间:2014-10-19 22:15:46

标签: sql asp.net sql-server asp-classic adodb

我有三张桌子:

team(ID, name)
goal(ID, team_ID, goalType_ID, date)
goalType(ID, name)

如您所见,team_ID是teams表的ID,goalType_ID是goalType表的ID。

对于所有团队,我想列出曾经发生的不同类型目标的数量,如果没有,则应该出现0。

我们不需要关心目标表,因为我们不需要目标类型的名称所以我已经得到了仅使用前两个表的以下代码:

SELECT team.ID, team.name, goal.goaType_ID
FROM team LEFT JOIN goal ON team.ID=goal.team_ID

这会产生一个我想要的三列信息表,但我想计算DISTINCT目标类型的数量,以及GROUP BY team.ID或team.name,并保留三列,如果结果为null,显示0(团队可能没有进球)。

结果表看起来像这样:

team.ID     team.name   goalsType.ID
1           Team_1      1
2           Team_2      2
2           Team_2      2
2           Team_2      2
3           Team_3      4
4           Team_4      null
5           Team_5      null
6           Team_6      1
6           Team_6      2
6           Team_6      4
6           Team_6      3
7           Team_7      5
7           Team_7      4
8           Team_8      null

我尝试过GROUP BY,DISTINCT和COUNT的组合,但仍然无法得到我想要的结果。

也许我说这一切都错了?任何帮助将不胜感激,谢谢。

编辑: 根据Gordon Linoff的回答,我试着做了:

SELECT DISTINCT team.name, COUNT(goal.goalType_ID)
FROM team LEFT JOIN goal ON team.ID=goal.team_ID
GROUP BY team.ID, team.name

它会给我:

Name        #0
Team_1      1
Team_2      3
Team_3      1
Team_4      0
Team_5      0
Team_6      4
Team_7      1
Team_8      0

如果我尝试使用“DISTINCT team.ID,DISTINCT team.name”,则会出错。

2 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT team.ID, team.name, count(distinct goal.goalType_ID) as NumGoalTypes
FROM team LEFT JOIN
     goal
     ON team.ID = goal.team_ID
GROUP BY team.ID, team.name;

答案 1 :(得分:1)

试试这个http://sqlfiddle.com/#!3/8ec680/13

;WITH cte 
      AS (SELECT Row_number() OVER(partition BY tname 
                    ORDER BY goalid), * from temp)--temp= Your join statement  
SELECT CASE 
         WHEN a.goalid IS NULL THEN 0 
         ELSE a.row_n 
       END [count], 
       a.tid, 
       a.tname, 
       a.goalid 
FROM   cte a 
       JOIN (SELECT Max(row_n) row_n, 
                    tname 
             FROM   cte 
             GROUP  BY tname) b 
         ON a.row_n = b.row_n 
        AND a.tname = b.tname