1

I have a tables

create table posts (
   text varchar(20),
   created_at datetime,
   user_id integer
);

create table users (
   id integer,
   name varchar(20),
   important bolean
);

create table categories (
   id integer,
   name varchar(20),
);
create table categories_posts (
   category_id integer,
    post_id integer
);

Want to calculate the number of posts for each category between certain times with results like this

START_TIME_PERIOD, category, count_all, count_important, count_normal
'2013-03-06 23:40', 'dogs',    20,       5,               15
'2013-03-06 23:40', 'cats',    22,       6,               16
'2013-03-06 23:40', 'birds',   24,       7,               17

where the importance is based on the users importance.

To get one count e.g. important

select '2013-03-06 23:40', categories.name, count(*)
from posts, users, categories
where posts.id = categories_posts.post_id
and categories.id = categories_posts.category_id
and posts.user_id = users.id
and users.important = true
and posts.created_at BETWEEN '2013-03-06 23:40' AND  '2013-03-06 23:20'
group by 1, 2

What is the best way to get the three counts in a single result set?

Thanks

1
  • 1
    SUM(IF(condition),1,0) == pseudocount Commented Mar 6, 2013 at 23:49

2 Answers 2

2
SELECT ..... , count(*), SUM(IF(user.important,1,0)) as count_important, COUNT(*) - SUM(IF(user.important,1,0)) as count_normal
Sign up to request clarification or add additional context in comments.

Comments

1

Rather than using COUNT, you can use SUM combined with CASE, e.g.

SELECT COUNT(*) AS count_all, 
    SUM(CASE WHEN important = 1 THEN 1 ELSE 0 END) AS count_important

1 Comment

Thanks - picked @Wrikken's as correct because it was slightly more terse.

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.