简体   繁体   中英

Table statistics (aka row count) over time

i'm preparing a presentation about one of our apps and was asking myself the following question: "based on the data stored in our database, how much growth have happend over the last couple of years?"

so i'd like to basically show in one output/graph, how much data we're storing since beginning of the project.

my current query looks like this:

SELECT DATE_FORMAT(created,'%y-%m') AS label, COUNT(id) FROM table GROUP BY label ORDER BY label;

the example output would be:

  • 11-03: 5
  • 11-04: 200
  • 11-05: 300

unfortunately, this query is missing the accumulation. i would like to receive the following result:

  • 11-03: 5
  • 11-04: 205 (200 + 5)
  • 11-05: 505 (200 + 5 + 300)

is there any way to solve this problem in mysql without the need of having to call the query in a php-loop?

Yes, there's a way to do that. One approach uses MySQL user-defined variables (and behavior that is not guaranteed)

SELECT s.label
     , s.cnt
     , @tot := @tot + s.cnt  AS running_subtotal
  FROM ( SELECT DATE_FORMAT(t.created,'%y-%m') AS `label`
              , COUNT(t.id) AS cnt
           FROM articles t
          GROUP BY `label`
          ORDER BY `label`
       ) s
 CROSS
  JOIN ( SELECT @tot := 0 ) i

Let's unpack that a bit.

The inline view aliased as s returns the same resultset as your original query.

The inline view aliased as i returns a single row. We don't really care what it returns (except that we need it to return exactly one row because of the JOIN operation); what we care about is the side effect, a value of zero gets assigned to the @tot user variable.

Since MySQL materializes the inline view as a derived table, before the outer query runs, that variable gets initialized before the outer query runs.

For each row processed by the outer query, the value of cnt is added to @tot .

The return of s.cnt in the SELECT list is entirely optional, it's just there as a demonstration.

NB The MySQL reference manual specifically states that this behavior of user-defined variables is not guaranteed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM