[英]MySql query with multiple counts in result
我有一張桌子
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
其重要性取決於用戶的重要性。
獲得一個例如重要的計數
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
在單個結果集中獲取三個計數的最佳方法是什么?
謝謝
SELECT ..... , count(*), SUM(IF(user.important,1,0)) as count_important, COUNT(*) - SUM(IF(user.important,1,0)) as count_normal
您可以使用SUM
與CASE
結合使用,而不是使用COUNT
SELECT COUNT(*) AS count_all,
SUM(CASE WHEN important = 1 THEN 1 ELSE 0 END) AS count_important
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.