以下是表myTable
中的内容。
+--------+--------+--------+--------+
| value1 | value2 | value3 | value4 |
+--------+--------+--------+--------+
| 9 | 4 | 3 | 3 |
| 1 | 2 | 9 | 3 |
| 1 | 2 | 3 | 4 |
| 1 | 2 | 3 | 4 |
+--------+--------+--------+--------+
我希望输出为
+--------+--------+--------+--------+
| value1 | value2 | value3 | value4 |
+--------+--------+--------+--------+
| 1 | 2 | 3 | 4 |
+--------+--------+--------+--------+
value1=1
因为1在该列中是三倍。
value2=2
因为该列中有两次。
value3=3
因为该列中有3个是三次。
value4=4
因为4在该列中是两次,而且是该列中所有公共号码的最大数量。
注意:value4
最常见的值为3和4.在输出中我应该得到4,因为4是3,4中的最大值。
我可以在mysql中实现这个吗?
我也在这里列出答案,所以不需要继续使用js-fiddle。 (根据@ypercube回答)
SELECT
( SELECT value1
FROM myTable
GROUP BY value1
ORDER BY COUNT(*) DESC
, value1 DESC
LIMIT 1
) AS value1,
( SELECT value2
FROM myTable
GROUP BY value2
ORDER BY COUNT(*) DESC
, value2 DESC
LIMIT 1
) AS value2,
( SELECT value3
FROM myTable
GROUP BY value3
ORDER BY COUNT(*) DESC
, value3 DESC
LIMIT 1
) AS value3,
( SELECT value4
FROM myTable
GROUP BY value4
ORDER BY COUNT(*) DESC
, value4 DESC
LIMIT 1
) AS value4
;
答案 0 :(得分:3)
SELECT
( SELECT value1
FROM myTable
GROUP BY value1
ORDER BY COUNT(*) DESC
, value1 DESC
LIMIT 1
) AS value1,
( SELECT value2
FROM myTable
GROUP BY value2
ORDER BY COUNT(*) DESC
, value2 DESC
LIMIT 1
) AS value2,
...
( SELECT valueN
FROM myTable
GROUP BY valueN
ORDER BY COUNT(*) DESC
, valueN DESC
LIMIT 1
) AS valueN
;
SQL-Fiddle:test-2
答案 1 :(得分:-1)
这可能不是存储数据的理想方式 您可能需要考虑使用键值对来标准化4列 (这意味着每列一行)
(你可以使用UNION来实现你想要的目标)
(select value1, null, null, null from TABLE group by value1 order by count(*) desc, value1 desc limit 1)
union
(select null, value2, null, null from TABLE group by value2 order by count(*) desc, value2 desc limit 1)
union
(select null, null, value3, null from TABLE group by value3 order by count(*) desc, value3 desc limit 1)
union
(select null, null, null, value4 from TABLE group by value4 order by count(*) desc, value4 desc limit 1)