Is it possible to count results (e.g. count the nodes of the content type x) in a view, using aggregation (not programmatically)?
-
3Sure, just use aggregation and then select "count" for your "node id" field.– uweCommented Jan 26, 2012 at 1:05
-
1There is an identical Q&A at drupal.stackexchange.com/questions/15871/count-of-nodes-by-type, including a ready-to-use view export.– marcvangendCommented Jan 22, 2013 at 22:59
3 Answers
Yes, it is possible in Views 3 out of the box.
The idea is the same as in SQL aggregations. Lets see an example:
Edit your view and enable Views aggregations:
Remove default sort criteria.
- Add fields “Content: Type” and “Content: Nid”:
Select COUNT function for Content: Nid:
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.
-
2I was stuck for couple of hours, then after reading your post I realized that I had default sorting there. Thanks @kalabro– saadluluCommented Oct 24, 2012 at 12:33
-
2So 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
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.
-
To clarify, this extends the great solution provided by kalabro, to display a count. Commented Mar 19, 2018 at 13:00
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!