在给定的锦标赛中,每位足球运动员按升序排列的目标数达到了多少(总和)。 对于那些有0个进球的球员,我们应该返回值为0的足球运动员的名字。点数,0球的足球运动员也应该是输出的一部分。
Footballer name | Goal | Tournament
Messi | 3 | La liga
Ronaldo | 5 | UEFA
Suarez | 2 | La liga
输出应该是“西甲联赛”。输出应该是:
Ronaldo 0
Suarez 2
Messi 3
答案 0 :(得分:1)
试试这个
select footballer, sum(goals)
from (
select footballer, CASE
WHEN tournament = 'LA_LIGA' THEN goals
else 0
END
from tableA) AS tabA
group by footballer
希望有所帮助。
答案 1 :(得分:0)
我不确定数据库的结构是什么,我认为通常得分会奖励给团队而不是个人。无论如何,这里只是概念:
表:
玩家= {playerID,姓名,年龄,性别,身高等。}
游戏= {gameID,playerID,得分......}
锦标赛= {tournamentID,gameID,锦标赛名称......}
select p.name, IFNULL(g.score,0), t.tournamentName
from players p
left join Games g on p.playerID = g.playerID
left join Tournaments t on g.GameID = t.GameID
where t.tournamentName = 'La liga'
解决方案: 我的观点是你可能需要使用 IFNULL(..)并将默认值设置为0.
答案 2 :(得分:0)
试试这个......
Select FootballerName,
sum(CASE WHEN tournament = 'LA LIGA' THEN Goal else 0 END) as Goal
from #Matches group by FootballerName
想要在所有比赛中获得球员的所有目标
Select FootballerName, sum(Goal) as Goal
from #Matches group by FootballerName
想要了解目标吗?
Select FootballerName, sum(Goal) as Goal,Tournament
from #Matches group by FootballerName,Tournament
答案 3 :(得分:-1)
除非您有3个牌桌(玩家,锦标赛和目标),否则您需要使用子选择创建3个集合并将它们连接在一起。你需要所有锦标赛和所有足球运动员的交叉产品。
SELECT footballer_name, tournament FROM
(SELECT DISTINCT footballer_name FROM your_table) AS players
JOIN
(SELECT DISTINCT tournament FROM your_table) AS tournaments
以上每个独特的足球运动员和锦标赛配对应该会有一个记录。看看你是否可以在你的数据库中使用它,然后通过最终的分数加入
来完成它答案 4 :(得分:-1)
Source Of Information: Pivot查询帮助我们生成一个交互式表格,可以快速组合和比较大量数据。我们可以旋转其行和列以查看源数据的不同摘要,并且我们可以一目了然地显示感兴趣区域的详细信息。它还有助于我们生成多维报告。
创建表格脚本
Create table Matches(FootballerName varchar(100),Goal int ,Tournament varchar(100))
Sql Server插入记录脚本
insert into Matches(FootballerName,Goal,Tournament)
select 'Messi ', 3 ,'La liga' union
select 'Ronaldo ', 5 ,'UEFA' union
select 'Surez ', 2 ,'La liga'
MySql Server脚本
Create table Matches(FootballerName varchar(100),Goal int ,Tournament varchar(100));
insert into Matches(FootballerName,Goal,Tournament)
select 'Messi ', 3 ,'La liga' union
select 'Ronaldo ', 5 ,'UEFA' union
select 'Surez ', 2 ,'La liga';
MYSQL版
Select FootBallerName,
Sum(CASE WHEN Tournament= 'La liga' THEN goal ELSE 0 END) AS 'La liga',
Sum(CASE WHEN Tournament= 'UEFA' THEN goal ELSE 0 END) AS 'UEFA'from Matches
group by FootBallerName order by FootBallerName;
使用Pivot的SQL Server查询---仅用于[La liga]
SELECT FootballerName,isnull([La liga],0) as'La liga'
FROM (
SELECT
FootballerName ,isnull(goal,0) as'goal',
Tournament
FROM Matches
) as s
PIVOT
(
SUM(goal)
FOR Tournament IN ([La liga],[UEFA])
)AS pvt order by [La liga]
使用Pivot的SQL Server查询---仅[La liga]和[UEFA]
SELECT FootballerName,isnull([La liga],0) as'La liga',isnull([UEFA],0) as'UEFA'
FROM (
SELECT
FootballerName ,isnull(goal,0) as'goal',
Tournament
FROM Matches
) as s
PIVOT
(
SUM(goal)
FOR Tournament IN ([La liga],[UEFA])
)AS pvt order by [La liga],[UEFA]
您可以阅读更多[https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx]