hye everyone..i just want to share my problem using php..:$

i have data for field total

i.e total = (2,3,4,5,62,45,67,89,10,23,11,23,98,12)

from all data i want 5 max values only. please help me to meet the solution.:)

Dani AI

Generated

Short answer for : the usual approach is to sort totals in descending order and return only the first five rows β€” that is exactly what was pointing to. A couple of important follow-ups and alternatives depending on exact needs and MySQL version follow.

If you want to include ties (or treat duplicate totals as a single value), MySQL 8+ window functions give precise control. For example, to get rows whose totals are among the top five distinct totals use a ranking function:

WITH ranked AS (
  SELECT *,
         DENSE_RANK() OVER (ORDER BY total DESC) AS rnk
  FROM grandtotal
)
SELECT *
FROM ranked
WHERE rnk <= 5;

If you are on an older MySQL (pre-8.0) and need the top five distinct totals, a correlated subquery can do the job without window functions:

SELECT t1.*
FROM grandtotal AS t1
WHERE (
  SELECT COUNT(DISTINCT t2.total)
  FROM grandtotal AS t2
  WHERE t2.total > t1.total
) < 5
ORDER BY t1.total DESC;

Practical tips: make sure total is stored as a numeric type (or cast it when ordering) to avoid lexicographic sorting; cast input for any programmatic limit (e.g., (int)$n in PHP) to avoid injection; add an index on the total column for large tables to improve performance; and if you only need the single highest value, use the aggregate MAX(total) as hinted. For reference on syntax and window functions see the MySQL docs: SELECT syntax and LIMIT and Window functions.

Recommended Answers

All 4 Replies

What are you looking for, how to do this with a query ? Can you show the code you have so far ?

actually im looking the max value from my table (grandtotal). i just want to display 5 values from that.

It'll probably be something like this:

SELECT total FROM grandtotal ORDER BY total DESC LIMIT 5

Did you want just the MAXimum value out of that set of numbers you provided us??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.