问题
I need to count how many people belong in pre-defined groups (this is easy to do in SQL using the SELECT COUNT statement). My Views query runs fine and displays the actual data in my table, but I simply need to know how many results it found.
However there doesn't seem to be a COUNT option in views. I am guessing I am going to have to use some sort of views hook, and then stick the result in the table.
Here's a quick example of what i'm trying to achieve:
My Table
----------------------
Group A | 20 people
Group B | 63 people
and so on.
(I've tried using the Views_Calc module, but I get errors because it is not quite stable yet.)
Anybody know of an easy way to count results in Views?
回答1:
Here's a good d.o thread about it: http://drupal.org/node/131031
Although if you JUST need the count and not the other things Views offers (field formatting & ordering, etc), why not just code up the proper SELECT COUNT statement and call it a day?
(If you DO in fact need those other pieces Views offers, there are many examples on that thread above.)
回答2:
I'm currently using the Views Group By module for this type of functionality.
I'm actually working on adding other aggregate functions (MIN
, MAX
, etc.) into it but since you only need the COUNT
function, I think it's a pretty good option.
All you have to do (after installing and enabling the module), in the View that you are interested:
- Add fields for the criteria that you want to
GROUP BY
. - Add the SQL Aggregation field as the last field (or swap it into the last).
- Choose the fields (you can select multiple fields)
Fields to Group On
. SQL Aggregation Function
should be set toCount
.- Fields to
Aggregate with the SQL function
set to a field that you are not grouping by. (This will be added into theCOUNT
function likeCOUNT(<this field>)
in SQL) - The rest is up to you and click
Update
.
You should have the COUNT
output from the field that you selected to aggregate.
来源:https://stackoverflow.com/questions/2952901/count-number-of-results-in-a-view