以下是表及其值:
CREATE TABLE Weapon(id INT,
Name VARCHAR(80),
Style VARCHAR(80));
Insert into Weapon values (1, 'Seismic Wand', 'Magic');
Insert into Weapon values (2, 'Nox Bow', 'Ranged');
Insert into Weapon values (3, 'Drygore', 'Melee');
Insert into Weapon values (4, 'Chaotic Staff', 'Magic');
Insert into Weapon values (5, 'Staff of Darkness', 'Magic');
Insert into Weapon values (6, 'Tetsu Katana', 'Melee');
这是我的查询尝试。
SELECT Name, Count(*) AS Style
FROM Weapon
GROUP BY Name
HAVING Count(*) >= ALL
(SELECT Count(*)
FROM Weapon
GROUP BY Name);
它没有显示模式,Style
列的最重复值。
如何制作以显示模式?
答案 0 :(得分:4)
<强>更新强>
为了回应@ vkp对多个Style
作为数据集模式的可能性的合理担忧,这里有一个更好的查询:
SELECT Style AS Mode, COUNT(*) AS Count FROM Weapon GROUP BY Style HAVING COUNT(*) >= ALL (SELECT COUNT(*) FROM Weapon GROUP BY Style);
+-------+-------+
| Mode | Count |
+-------+-------+
| Magic | 3 |
+-------+-------+
这将返回数据集的模式,并将处理多个Style
是模式而不需要目视检查结果的情况。
例如,建立原始表格,
INSERT INTO Weapon VALUES (7, 'Rock', 'Melee');
(增加&#39;近战的数量&#39;因此它将与魔术&#39;相关联)
如果我们运行新的模式查找查询,我们会得到以下结果:
+-------+-------+
| Mode | Count |
+-------+-------+
| Magic | 3 |
| Melee | 3 |
+-------+-------+
我发布的原始答案(保留在下面)将生成表格顶部的模式,并要求用户挑选他们需要的值。在我看来,这种新的解决方案效果更好。另外,我意识到最初我已经标记了我的&#34; Count&#34;列为&#34;模式&#34;当数据集的模式确实是样式的名称(魔术,近战等)时,不是样式发生的次数。
原始答案:
对于Style列的模式,
SELECT Style, COUNT(*) AS Mode FROM Weapon GROUP BY Style ORDER BY COUNT(*) DESC;
+--------+------+
| Style | Mode |
+--------+------+
| Magic | 3 |
| Melee | 2 |
| Ranged | 1 |
+--------+------+
模式将位于表格的顶部。
感谢http://www.xarg.org/2012/07/statistical-functions-in-mysql/
答案 1 :(得分:0)
我假设mode
,您打算找到按名称分组的表格中的所有最大重复项目。
select t2.name from
(select max(style) as maxstyle from
(SELECT Name, Count(*) AS Style
FROM Weapon
GROUP BY Name) t) t1
join (SELECT Name, Count(*) AS Style
FROM Weapon
GROUP BY Name) t2 on t1.maxstyle = t2.style