我有一个 MS-SQL 游戏结果表,其中包含主队,主队得分,客场球队和客队得分。我试图查询首先排序的队伍,胜利和损失,总胜利(降序)然后是总损失(升序)。表不包含赢或输列。必须根据分数计算胜利和损失。如果我需要创建视图或临时表,如何使用团队,胜利和损失创建该视图?
答案 0 :(得分:1)
假设您可以在查询中撤回该信息,则可以在ORDER BY
子句中使用聚合:
ORDER BY
SUM(win) DESC
,SUM(loss) ASC
修改:更新评论
如果只存储了分数,您将要使用临时表或CTE(取决于您使用的DBMS,如果支持它们)首先创建一个包含团队和胜负的表。它们,然后您可以SELECT
从而ORDER
相应地。
答案 1 :(得分:1)
SELECT *
FROM MyTable
WHERE ...
ORDER BY SUM(win) DESC, SUM(loss) ASC
有关更详细的答案,请提供您的架构和示例数据。
答案 2 :(得分:0)
作业?
无论如何,您可以通过跟随订单的列来指定SQL语句中的排序顺序。例如,
select x, y, z from table order by x asc, y desc, z asc
答案 3 :(得分:0)
select
teamName,
'wins' =
case
when wins is null then 0
else wins
end,
'losses' =
case
when losses is null then 0
else losses
end
from
teams
left join
(
select
a.wins as wins,
b.losses as losses,
'team' =
case
when a.team is null then b.team
else a.team
end
from
(
select
homeTeam as team,
sum(wins) as wins
from
(
select
homeTeam,
count(*) as wins
from
results
where
homeScore > awayScore
group by
homeTeam
union all
select
awayTeam,
count(*) as wins
from
results
where
homeScore < awayScore
group by
awayTeam
) a
group by homeTeam
) a
full outer join
(
select
homeTeam as team,
sum(losses) as losses
from
(
select
homeTeam,
count(*) as losses
from
results
where
homeScore < awayScore
group by
homeTeam
union all
select
awayTeam,
count(*) as losses
from
results
where
homeScore > awayScore
group by
awayTeam
) a
group by
homeTeam
) b
on a.team = b.team
) c
on teams.id = c.team