2

下面是我在 table 中的内容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因为 2 在该列中是三次。

value3=3因为 3 在该列中是三次。

value4=4因为 4 在该列中是两倍,这是该列中所有常见数字的最大数量。

注意value4最常见的值为 3 和 4。在输出中我应该得到 4,因为 4 是 3,4 中最大的。

我可以在mysql中实现这一点吗?

更新 1

SQL Fiddle 上的表

更新 2

我也在此处列出答案,因此无需继续使用 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
;
4

2 回答 2

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

于 2012-05-30T11:31:30.103 回答
-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)
于 2012-05-30T11:29:24.847 回答