1

私はテーブルを持っています

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
);

このような結果で、特定の時間の間の各カテゴリの投稿数を計算したい

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

ここで、重要度はユーザーの重要度に基づいています。

重要な例として1つのカウントを取得するには

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

1つの結果セットで3つのカウントを取得するための最良の方法は何ですか?

ありがとう

4

2 に答える 2

2
SELECT ..... , count(*), SUM(IF(user.important,1,0)) as count_important, COUNT(*) - SUM(IF(user.important,1,0)) as count_normal
于 2013-03-06T23:52:42.557 に答える
1

を使用するのではなく、と組み合わせてCOUNT使用​​できます。SUMCASE

SELECT COUNT(*) AS count_all, 
    SUM(CASE WHEN important = 1 THEN 1 ELSE 0 END) AS count_important
于 2013-03-06T23:51:15.227 に答える