SQL Server : Select and count

标签 sql sql-server

我有 3 个表:

> HockeyTeam with columns: ID and Name 
> HockeyGame with columns: ID,Team1ID and Team2ID (both linked to HockeyTeam ID) 
> GameScores with columns: ID, GameID, Team1Score, Team2Score

曲棍球队

ID   Name
1    Monkeys
2    Beavers
3    Dolphins
4    Snakes

游戏分数

ID   GameID   Team1Score   Team2Score
1    1        3            2
2    2        4            0
3    3        2            3
4    4        2            4

曲棍球比赛

ID   StartTime   Team1ID   Team2ID
1    2/6/2015    1         2
2    2/13/2015   3         4
3    2/20/2015   2         4
4    2/27/2015   1         3

我需要显示每个团队的总目标。团队可以同时属于 Team1IDTeam2ID。这是我到目前为止所得到的:

SELECT  
    ht.Name, 
    SUM(SELECT (gs.Team1Score + gs.Team2Score) 
        FROM GameScores as gs
            INNER JOIN HockeyGame as hg
            INNER JOIN  HockeyTeam  as ht
            ON ht.ID = hg.Team1ID OR ht.ID = ht.Team2ID
            ON gs.GameID = hg.ID
FROM 
    HockeyTeam  as ht

最佳答案

让我们采用如下结构:

create table team (id int, name varchar(20));
insert into team values (1, 'H1'), (2, 'H2'), (3, 'H3');

create table game (id int, team1id int, team2id int);
insert into game values (11, 1, 2), (12, 1, 3), (13, 2, 3);

create table score (
  id int,
  gameid int,
  team1score int,
  team2score int
);
insert into score values 
(21, 11, 5, 2), 
(22, 12, 2, 5), 
(23, 13, 0, 2);  

显示游戏结果(还不是答案)

-- show readable game results
select
  s.gameid,
  t1.name as team1,
  t2.name as team2,
  team1score,
  team2score
from score s
inner join game g on s.gameid = g.id
inner join team t1 on g.team1id = t1.id
inner join team t2 on g.team2id = t2.id;

数据如下所示:

gameid  team1  team2  team1score  team2score
11      H1     H2     5           2
12      H1     H3     2           5
13      H2     H3     0           2

现在让我们得到分数(答案)

-- show score by team 
select
  t.name,
  sum(score) as goals
from team t

left join 
(
  -- get score of team1
  select
    t1.id as teamid,
    sum(team1score) as score
  from score s
  inner join game g on s.gameid = g.id
  inner join team t1 on g.team1id = t1.id
  group by t1.id

  union all

  -- get score of team2 and combine it with results from team1
  -- this is because team2 can be team1 for some games
  select
    t2.id as teamid,
    sum(team2score) as score
  from score s
  inner join game g on s.gameid = g.id
  inner join team t2 on g.team2id = t2.id
  group by t2.id
) t1 on t.id = t1.teamid

group by t.name

结果将如下所示:

Name  Goals
H1    7
H2    2
H3    7

示例:http://sqlfiddle.com/#!9/aa3cc/15 尽管该示例适用于 MySQL(因为 SQL Server Fiddle 正在运行),但 SQL 语句对于 SQL Server 也仍然有效。

关于SQL Server : Select and count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30541771/

相关文章:

sql - 如何明智地按一组增加列

php - 获取 $rank 变量并在表中更新它

php - 我是否正确使用 MATCH() ?

.net - 加密 Windows 身份验证连接字符串

sql - 导入时自动调整数据类型

sql - 查询 SQL Server 2012 数据库时出现初始错误

SQL 分组查询

用于对连续数字进行分组的 SQL 查询

.net - 面试时如何练习大型SQL Server索引或分区问题?

sql - 在 T-SQL (SQL Server 2008) 中连接到远程服务器