31

Is it possible to count results (e.g. count the nodes of the content type x) in a view, using aggregation (not programmatically)?

2

3 Answers 3

52

Yes, it is possible in Views 3 out of the box.
The idea is the same as in SQL aggregations. Lets see an example:

  1. Edit your view and enable Views aggregations:
    enable Views aggregations

  2. Remove default sort criteria.

  3. Add fields “Content: Type” and “Content: Nid”: enter image description here
    Select COUNT function for Content: Nid: enter image description here

To see what happens just turn on checkbox “Show the SQL query” at global Views settings page.

SELECT node.type AS node_type, COUNT(node.nid) AS nid
FROM 
{node} node
WHERE (( (node.status = '1') ))
GROUP BY node_type
LIMIT 10 OFFSET 0

So, we are grouping nodes by node_type and calculating count for this groups.

3
  • 2
    I was stuck for couple of hours, then after reading your post I realized that I had default sorting there. Thanks @kalabro
    – saadlulu
    Commented Oct 24, 2012 at 12:33
  • 2
    So how is the count made available - is it a token variable and how can it be displayed? Commented Jul 25, 2013 at 10:53
  • Your reply is, of course, correct. However, I've been stuck when using Relationships with Entity References and Aggregation. It works fine if you build a block, but not if you make a Page. Weird stuff. Commented Mar 31, 2015 at 17:51
12

Great answers here though your original question does not state what you are going to do with the count value. Presumably you want to display it?

If so, here's another solution:

Assuming that your View is already set up to filter by items of content type, then you can also add a header in the View and choose the "Global: Result summary" option and use the token variables provided in the text area.

1
  • To clarify, this extends the great solution provided by kalabro, to display a count. Commented Mar 19, 2018 at 13:00
-2

Just in case someone comes across this.

I used the Views Date Format SQL to format the date to the granularity.

The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.

The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE_FORMAT rather than PHP's format_date.

This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views_handler_field_date.

Worked right out of the box - easy as!

Not the answer you're looking for? Browse other questions tagged or ask your own question.