gpt4 book ai didi

结果中有多个计数的 MySql 查询

转载 作者:行者123 更新时间:2023-11-29 05:30:32 24 4
gpt4 key购买 nike

我有一张 table

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

关于结果中有多个计数的 MySql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15260346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com