我需要计算不同列之间最后一位数的重复值的次数。我对最高计数感兴趣。
Col1 Col2 Col3 Col4 Col5
---- ---- ---- ---- ----
1 13 23 21 31 = result should be 3 for 3 time the 1.
希望这是有道理的。
如果SQL可以实现这些想法吗?
提前感谢您的所有帮助!
答案 0 :(得分:1)
我可能有一个解决方案,假设有一个主键:
SELECT id, MAX(count) FROM (
SELECT id, val, COUNT(*) AS count FROM (
SELECT id, MOD(col1, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col2, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col3, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col4, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col5, 10) AS val FROM your_table) vals
GROUP BY id, val) counts
GROUP BY id;
请注意,这些函数是特定于mysql的,但几乎任何其他db都应该存在类似的函数。
Innermost SELECT使用id和val列构建派生表,其中val是每列的最后一位数。接下来的SELECT out将按id计算每个值。最外面的SELECT按id返回最大值计数。
然后,如果您希望在列值旁边显示结果,则只需将此查询与原始表连接:
SELECT col1, col2, col3, col4, col5, max_count
FROM your_table yt
JOIN (
SELECT id, MAX(count) max_count FROM (
SELECT id, val, COUNT(*) AS count FROM (
SELECT id, MOD(col1, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col2, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col3, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col4, 10) AS val FROM your_table
UNION ALL SELECT id, MOD(col5, 10) AS val FROM your_table) vals
GROUP BY id, val) counts
GROUP BY id) mc ON yt.id = mc.id;
这是输出:
+------+------+------+------+------+-----------+
| col1 | col2 | col3 | col4 | col5 | max_count |
+------+------+------+------+------+-----------+
| 1 | 13 | 23 | 21 | 31 | 3 |
+------+------+------+------+------+-----------+