nonaxanon
nonaxanon

Reputation: 247

how to select sum limit to X number mysql

$query = "SELECT sum(DAILYTIME)  FROM $mytable  LIMIT 5";

that statement selects and sums limited to 5 rows, but how to do it based on certain row. For example I want to use row #10 as a starting point and sum 5 rows below that one ( 5 rows including that same row ).

how would the statement need to be, because if i do WHERE DAY = '$day' LIMIT 5 it will not sum all the 5 rows, just 1

Upvotes: 4

Views: 2243

Answers (2)

Uueerdo
Uueerdo

Reputation: 15951

This will give you the sum of the 10th through 14th "rows"; however, since there is no ORDER BY, there is no guarantee which rows of the table the result rows of the subquery would be.

SELECT sum(DAILYTIME) 
FROM (
    SELECT DAILYTIME 
    FROM $mytable 
    LIMIT 9, 5
  ) AS `rows10to15`
;

Upvotes: 0

Noah Wetjen
Noah Wetjen

Reputation: 1785

By adding a where clause with the >= operator, you will also select all following rows. Use the following query:

$query = "SELECT sum(DAILYTIME) FROM $mytable WHERE DAY >= '$day' LIMIT 5";

Upvotes: 2

Related Questions