I am in a position where I want multiple counts from a single table based on different combination of conditions.
The table has 2 flags: A & B.
I want count for following criteria on same page:
- A is true (Don’t care about B)
- A is false (Don’t care about B)
- A is true AND B is true
- A is false AND B is true
- A is true AND B is false
- A is false AND B is false
- B is true (Don’t care about A)
- B is false (Don’t care about A)
I want all above count on same page. Which of following will a good approach for this:
- Query for count on that table for each condition. [That is firing 8 queries every time user gives the command.]
- Query for list of data from database and then count values for appropriate conditions on UI.
Which option should I choose? Do you know any other alternative for this?
Your table essentially looks like this (The ID column is redundant, but I expect you have other data in your actual table anyway.):
Some sample data:
This query (in mysql, I’m not sure about other DBMS) should produce the results you want.
With the sample, simple data above, the query generates:
Notes:
This just causes every row ro be in the group.
This function counts all the NON null values in the group, which is why we use the if(…) to return null if the condition is not met.