我正在尝试对列进行求和以在体育网站上显示统计信息。我的mysql查询是
SELECT s.schoolid, s.season, s.playerid, SUM(s.serviceaces) AS sumAces, SUM(s.attackkills) AS sumKills, SUM(s.assists) AS sumAssists, p.fname, p.lname
FROM `stats` AS s
LEFT JOIN `players` AS p ON p.id = s.playerid
GROUP BY s.playerid
HAVING s.schoolid = 2 AND s.season = 2015
这将给我9条记录。它应该给我12,因为第2队有12名球员,并且都输入了统计数据。如果我将查询更改为
的简单选择查询SELECT s.*, p.fname, p.lname
FROM `stats` AS s
LEFT JOIN `players` AS p ON p.id = s.playerid
WHERE s.schoolid = 2 AND s.season = 2015
我返回24条记录。这是有道理的,因为为这支12人队输入了两场比赛的统计数据。
当我尝试将我的专栏和按玩家分组时,我做错了什么?
编辑 这是一个sql小提琴链接 - http://sqlfiddle.com/#!9/e5cf5/1/0)
我发现了问题,失踪人员有2014年的统计数据。我会阅读Ollie的链接,看看这是不是我的问题。
所以看起来我的解决方案就像添加WHERE s.season = 2015 AND s.schoolid = 2一样简单,以便最终查询
SELECT s.schoolid, s.season, s.playerid, SUM(s.serviceaces) AS sumAces, SUM(s.attackkills) AS sumKills, SUM(s.assists) AS sumAssists, p.fname, p.lname
FROM `stats` AS s
LEFT JOIN `players` AS p ON p.id = s.playerid
WHERE s.season = 2015
GROUP BY s.playerid
我在编辑时错过了Hitesh的回答。他做对了。
答案 0 :(得分:1)
对于这类问题,请发布表格模式和样本记录转储以及所需的结果,以便我们进行测试。 我认为这可以帮到你。
SELECT s.schoolid, s.season, s.playerid, SUM(s.serviceaces) AS sumAces, SUM(s.attackkills) AS sumKills, SUM(s.assists) AS sumAssists, p.fname, p.lname
FROM `stats` AS s
LEFT JOIN `players` AS p ON p.id = s.playerid
WHERE s.schoolid = 2 AND s.season = 2015
GROUP BY s.playerid
答案 1 :(得分:0)
切换您的from
和left join
条款 - 您希望从players
'侧驱动查询并显示缺少统计信息的null
,而不是其他方式:
SELECT s.schoolid,
s.season,
s.playerid,
SUM(s.serviceaces) AS sumAces,
SUM(s.attackkills) AS sumKills,
SUM(s.assists) AS sumAssists,
p.fname,
p.lname
FROM `players` AS p
LEFT JOIN `stats` AS s ON p.id = s.playerid
GROUP BY s.playerid
HAVING s.schoolid = 2 AND s.season = 2015