Question

I have the following data in the results table:

+-----+-----+-----+-----+-----+-----+
|  A  |  B  |  C  |  D  |  E  |  F  |
+-----+-----+-----+-----+-----+-----+
| 100 | 140 | 120 | 130 | 160 | 150 |
| 200 | 243 | 374 | 435 | 674 | 987 |
| 312 | 324 | 123 | 456 | 378 | 645 |
+-----+-----+-----+-----+-----+-----+

What sort of SELECT statement can get me the highest 5 values from the results table?

Was it helpful?

Solution

What sort of SELECT statement can get me the highest 5 values from the results table?

The fact that each column is treated identically suggests that your schema is denormalised. This operation would be greatly simplified if the data was normalised, such that the columns were merged (but an additional column created to indicate from which column each record originated).

However, as things stand, you can use a UNION:

  (SELECT A col FROM results ORDER BY col DESC LIMIT 5)
UNION ALL
  (SELECT B col FROM results ORDER BY col DESC LIMIT 5)
UNION ALL
  (SELECT C col FROM results ORDER BY col DESC LIMIT 5)
UNION ALL
  (SELECT D col FROM results ORDER BY col DESC LIMIT 5)
UNION ALL
  (SELECT E col FROM results ORDER BY col DESC LIMIT 5)
UNION ALL
  (SELECT F col FROM results ORDER BY col DESC LIMIT 5)
ORDER BY col DESC
LIMIT    5

See it on sqlfiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top