A. Rehman Javed
A. Rehman Javed

Reputation: 309

how to add group by values in a column in a mysql table

I have a mysql table which is as following

   **ip                  page                date                 page_Views
127.0.0.1              index.php           2012-07-09              25
182.445.11.1           abc.php             2012-07-09              11
116.142.24.7           index.php           2012-07-09              3 

I want to extract the page_views column grouped by page

that mean for 'index.php' it show page_view = 28

I'm using this query

SELECT * FROM stats_tracker GROUP BY page ORDER BY stats_tracker.page_views DESC

using this query i am grouping the page_views according to page but not adding so

page_views for index.php =25 according to my above query

Upvotes: 3

Views: 10581

Answers (1)

Chris Trahey
Chris Trahey

Reputation: 18290

You need the SUM aggregate function:

SELECT
  ip,
  page,
  CONCAT(MIN(date), " - ", MAX(date)) as date_range,
  SUM(page_views) as total_page_views
FROM stats_tracker
GROUP BY page
ORDER BY total_page_views DESC

The basic reasoning is that MySQL doesn't know how you want to combine values when you group. Sometimes you want to count, sometimes sum, and even averaging is available. Check out the MySQL Aggregate Functions page.

Upvotes: 9

Related Questions