mysql - 查询返回多个 id
问题描述
我有一个查询,可以在多个列(命名为 S1、S2、S3、S4、S5 和 S6)中找到最常见的数字。查询似乎工作得很好,但它不计算列中每个 id 的总数.
这是查询:
SELECT tag, qty, firstname, lastname, spelarid, position from (
SELECT s1 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
UNION
SELECT s2 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
UNION
SELECT s3 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
UNION
SELECT s4 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
UNION
SELECT s5 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
UNION
SELECT s6 AS tag, count(1) AS qty FROM matchmal where 23 IN (s1, s2, s3, s4, s5, s6) and goal='0' and lage ='EQ' GROUP BY tag
) temp LEFT JOIN spelare ON spelare.spelarid = tag
WHERE tag != 23 AND qty > 1
ORDER BY qty DESC
上面的查询返回 fe
标签 37 (Robin Johansson) 总值应为“21”,标签 28 Sebastian Borgs 总值应为“17”等。
我试过 GROUP BY spelarid 和标签,但它并没有加起来总数。
解决方案
您可以取消透视和计数。我想你想要这样的东西:
SELECT m.tag, COUNT(s.spelareid)
FROM (SELECT (CASE n WHEN 1 THEN s1 WHEN 2 THEN w2
WHEN 3 THEN s3 WHEN 4 THEN w4
WHEN 5 THEN s5 WHEN 6 THEN w6
END) AS tag
FROM matchmal m CROSS JOIN
(SELECT 1 as n UNION ALL
SELECT 2 as n UNION ALL
SELECT 3 as n UNION ALL
SELECT 4 as n UNION ALL
SELECT 5 as n UNION ALL
SELECT 6 as n
) n
WHERE 23 IN (s1, s2, s3, s4, s5, s6) AND
m.goal = 0 AND
m.lage = 'EQ'
) m LEFT JOIN
spelare s
ON m.tag = s.spelareid
GROUP BY m.tag
推荐阅读
- sum - 根据条件计算数组中的累积和
- java - 更简洁地打印对象数组
- assembly - ARM 子程序调用和链接寄存器使用
- excel - Excel公式从中间提取文本
- nlp - 有没有使用flair nlp获得单词或字符集的实际向量嵌入?即天赋嵌入
- azure-iot-edge - 较小平台上的 IoT Edge
- flutter - 任务“:firebase_storage:compileDebugJavaWithJavac”执行失败
- javascript - 使用 JS click() 打开 Select2 下拉菜单
- macos - ld:文件太小(长度=0)文件(在失败的gfortran编译中)
- r - 所有选定变量的滞后是否等于其当前值