我如何在SQL Server中使用存储过程

时间:2016-08-11 14:01:09

标签: sql sql-server stored-procedures sql-server-2014

我有以下五个表:

enter image description here

我需要实现一个存储过程,以便execute sp_getStandingUpToDate (aDate)计算并显示排名表,如下图所示:

enter image description here

截至日期aDate。

我需要调用任何无效日期,导致错误消息“无效日期!”已完成的所有事务将被回滚并停止进行进一步操作。

我该如何创建呢?

2 个答案:

答案 0 :(得分:1)

我可能不应该鼓励你发布这类问题。假设没有尝试,所有这些都已被提及。然后你没有完全描述这个问题:不是每个人都会知道GF,GA,GD是什么以及如何计算点数。

所以我认为这是一个有效的答案。如果您按原样将其打开,那么您的老师可能会知道您没有写它。但是我怀疑,如果你设法将它拆开并重写它,那么你将在这个过程中学到一些东西。所以冒着被投票的风险是:

with matchSummary as (
    select
        t.teamID,
        min(t.name) as teamName,
        sum(case when pt.teamID = t.teamID then 1 else 0 end) as GF,
        sum(case when pt.teamID = t.teamID then 0 else 1 end) as GA
    from
        team t
        inner join match m on t.teamID in (m.homeTeamID, m.visitingTeamID)
        inner join goals g on g.matchID = m.matchID
        inner join player_team pt on pt.playerID = g.playerID
    where m.dateOfMatch < @aDate
    group by m.matchID, t.teamID
)
select
    /* GD is first tie-breaker. Are there others? */
    row_number() over (
        order by
            sum(case when GF > GA then 3 when GF = GA then 1 end) desc,
            sum(GF) - sum(GA) desc
    ) as Pos,
    min(teamName) as "Team Name",
    count(*) as GP,
    count(case when GF > GA then 1 end) as W,
    count(case when GF = GA then 1 end) as T,
    count(case when GF < GA then 1 end) as L,
    sum(GF) as GF,
    sum(GA) as GA,
    sum(GF) - sum(GA) as GD,
    sum(case when GF > GA then 3 when GF = GA then 1 end) as Pts
from matchSummary
group by teamID;

答案 1 :(得分:-4)

select distinct t.name as TeamName,count(*) GP
from team t,match m,match m2
where t.teamID=m.homeTeamID and t.teamID=m2.visitingTeamID 
group by m.matchID,t.name

此代码为我提供了球队比赛的数量, 虽然我得到17而不是34。