我正在使用 MySQL,我有以下架构:
id school round score win loss tie
2 My School Name 1 10 1 0 0
3 My School Name 2 20 0 1 0
4 My School Name 3 30 1 0 0
5 My School Name 4 40 1 0 0
6 My School Name 5 50 1 0 0
7 My School Name 6 60 0 0 1
我需要以下输出,按学校名称分组
School Round1 Round2 Round3 Round4 Round5 Round6 wins losses ties
My School Name 10 20 30 40 50 60 4 1 1
到目前为止,我觉得我可以使用 GROUP BY School
和 SUM(win) as wins
来获得它的大部分功能。不过,困难的部分是获取那些 Round_
字段。
有人知道怎么做吗?在此先感谢,我们将不胜感激!
编辑:澄清一下,我知道我正好有 10 轮。
最佳答案
我们可以使用带有 GROUP BY 学校的 SELECT 语句为每所学校创建一条记录。如您所述,可以使用 SUM 聚合函数轻松计算领带、获胜和损失列。为了针对特定的回合,我们可以使用一些巧妙的数学运算(以避免像 CodeByMoonlight 建议的那样冗长的条件语句):
如果我们想以 R 轮为目标,我们注意到只有当 round == R 时“round-R”才为 0,否则它不是 0。当我们取“round-R”的 NOT 时,0 被反转为 1,而其他所有内容都设置为 0。现在,如果我们将 !(round-R) 乘以该回合的分数,当该回合不是 R(因为 0*score = 0)时,它会给我们 0当回合为 R 时会给我们“分数”(如 1*score = score)。接下来,当我们在列上取该值的 SUM 时,我们在 round=R 时添加分数,否则为 0,有效地只给我们轮 R 分数。
将所有这些放在一起给出:
SELECT school AS `School`,
SUM(!(round-1)*score) AS `Round1`,
SUM(!(round-2)*score) AS `Round2`,
SUM(!(round-3)*score) AS `Round3`,
SUM(!(round-4)*score) AS `Round4`,
SUM(!(round-5)*score) AS `Round5`,
SUM(!(round-6)*score) AS `Round6`,
SUM(!(round-7)*score) AS `Round7`,
SUM(!(round-8)*score) AS `Round8`,
SUM(!(round-9)*score) AS `Round9`,
SUM(!(round-10)*score) AS `Round10`,
SUM(win) AS `wins`,
SUM(loss) AS `losses`,
SUM(tie) AS `ties`
FROM `RoundScores` GROUP BY `school`
其中 RoundScores 是有问题的表。
编辑:
如果我们不想手动加10,我们可以使用prepared statements :
# Store all the conditionals in a string:
# I was not able to to have round loop from 1 to 10, so I iterated over
# all distinct values of 'round' present in the table.
SET @s = "";
SELECT `round`, (@s := CONCAT( @s , "SUM(!(round-",round, ")*score) AS `Round",round, "`," )) FROM `RoundScores` GROUP BY `round`;
# Combine the conditionals from before with the rest of the statement needed.
SET @qry = CONCAT("SELECT school AS `School`,",@s,"SUM(win) AS `wins`,SUM(loss) AS `losses` FROM `RoundScores` GROUP BY `school`");
# Prepare and execute the statement.
PREPARE stmt1 FROM @qry;
EXECUTE stmt1;
关于mysql - SQL 查询将记录分组在单独的字段下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659573/