0

I have a table called "trails" inside the table I have 3 columns called "id", "name" and "grading".

I have the following query which gives me the last 5 rows of a specific trail name based on the id. This works perfectly but now I need to get the sum total of the 5 results in the grading column?

SELECT * FROM `trails` WHERE `name` = "Free Flow" ORDER BY `id` DESC LIMIT 5
3
  • 2
    SELECT SUM(grading) FROM (SELECT ...) AS data Commented Jul 8, 2014 at 8:09
  • As a side note, ordering by an id column is often meaningless. It might be the insertion order, but this isn't actually guaranteed. And since db ids have no real meaning to the world outside, why would anybody else care about ordering by id? What do you mean by "last 5 rows"? Last 5 inserted - do you have a timestamp to record this? Last 5 with activity (ie, a row was updated, changing grading)? Rely on ids for only one thing - uniqueness (that is, only use them in ORDER BYs as a way to make sorts stable - you should have something else as the first sort column). Commented Jul 8, 2014 at 8:30
  • There will be no updating of rows, only want the last 5 entries which will have a unique incrementing id. It works fine for this small application, thanks for the note though. Commented Jul 8, 2014 at 9:24

2 Answers 2

2
SELECT sum(`grading`)
FROM
  (SELECT *
   FROM `trails`
   WHERE `name` = "Free Flow"
   ORDER BY `id` DESC LIMIT 5) AS TEMP;
Sign up to request clarification or add additional context in comments.

Comments

-1

you can use this query to get the sum of a particular column

SELECT SUM(originalOfferSize)
FROM `ActiveListings`
WHERE `originalOfferSize` = 4000000
ORDER BY `listingId` DESC LIMIT 5

2 Comments

I strongly suspect it will sum all rows because groupping happens before limiting (i'm not so sure so i didn't downvote).
@user2473917 It must be, I think it wouldn't be accepted otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.