首页 > 解决方案 > 在给定日期之前查找分数的存储过程

问题描述

编辑:乌龙球是球队总进球数。其他进球是其他球队总进球数

我有 2 张桌子,一张 TEAMS 和 MATCHES 桌子。

create table teams                                                                                                   
(                                                                                                                                  
Id char(3) primary key,                                                                                                  
name varchar(40),                                                                                                                   
nomatches int,                                                                                                                      
owngoals int,                                                                                                      
othergoals int,                                                                                                                  
points int                                                                                                                    
)

create table matches                                                                                                     
(                                                                                                                                    
id int identity(1,1),                                                                                            
homeid char(3) foreign key references teams(id),                                                                 
outid char(3) foreign key references teams(id),                                                                    
homegoal int,                                                                                                                     
outgoal int,                                                                                                                           
matchdate date                                                                                                               
)

我有用于插入和删除的触发器,可以为团队提供正确的分数。显示记分牌的选择如下所示。

select name, nomatches, owngoals, othergoals, points from teams 
order by points desc

它会给出这个结果,数字是比赛次数、球队进球数、对你的进球数、总分

在此处输入图像描述

现在我需要制作一个存储过程来制作记分牌,但只在给定日期之前。我尝试了一些不同的方法,例如将 Teams 表复制为@tmpTeams,但没有任何效果。

标签: mysqlsql

解决方案


你只想要一个聚合查询吗?你的问题没有解释列的逻辑是什么,但我猜是这样的:

select t.id, t.name,
       sum(mh.homegoal) as homegoals,
       sum(mo.outgoal) as othergoals,
       coalesce(sum(mh.homegoal), 0) + coalesce(sum(mo.outgoal), 0) as totalpoints
kfrom teams t left join
     matches mh
     on mh.homeid = t.id and
        mh.matchdate >= ? left join
     matches mo
     on mo.outid = t.id and
        mo.matchdate >= ?
group by t.id, t.name;

?旨在成为您的日期的参数。

注意:当可以使用查询计算此信息时,我认为没有理由使用触发器 - 除非您遇到需要触发器来解决的性能问题。


推荐阅读