1

Maybe I just can't think right currently. But what I want to try and figure out is how can I return a set of results that is the count of rows per category, in the DB. Without having to query based on each category.

The categories in this case are states. I have 90,000 rows of data with 50 different states dividing the data up. Is there a way of creating a count that is associated with each state?

I want to say group_by or something but I just honestly can't think of it right now. Ideas?

member | comment | state | dataset
----------------------------------
000    |something| CA    | an_object_of_data
000    |something| CA    | an_object_of_data
000    |something| CA    | an_object_of_data
000    |something| NY    | an_object_of_data
000    |something| NY    | an_object_of_data
000    |something| CA    | an_object_of_data
000    |something| CT    | an_object_of_data
000    |something| CA    | an_object_of_data

the above is an example of the db table in sorts. Imagine something like that with 90k rows and more state.

If I can some how get a count returned by grouping the results or something, ie: "CA=4", "CT=1", "NY=2"

1
  • yes you can. But it would be nice to know more about your db. show us a create table. Commented Jul 16, 2013 at 6:58

2 Answers 2

10
select state,  count(state) from states group by state order by state ASC;

I guess this might work in its simplest way!

CI Style:

$this->db->select("state, count(state)");
$this->db->from("states");
$this->db->group_by("state");
$this->db->order_by("state", "ASC");
$this->db->get();
Sign up to request clarification or add additional context in comments.

3 Comments

group_by? are you shure?
that actually works, exactly as I could have hoped! you have no idea how helpful that is, soo tired, crunching in last bits of stuff for a project. Just have to convert that to a CI active record variant of that query and Ill be good, I think I should be able to do that though using something like $this->db->query("select count(state),state from states group by state order by state ASC");
+1 and its good to see that there are also developers in Afghanistan :)
3

The code is

$this->db->select('count(states.state) as count,state',false)
         ->from(states)
         ->group_by('states.state')
         ->get()
         ->result();

1 Comment

@BobbyDigital i am new to stack overflow,will follow the rules surely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.