Sql 使用group by对查询中的列进行计数
我有下表Sql 使用group by对查询中的列进行计数,sql,postgresql,Sql,Postgresql,我有下表 id integer NOT NULL DEFAULT nextval('cl_id_seq'::regclass), from_number character varying(30), to_number character varying(30), message text, received_at timestamp with time zone, sent_at timestamp with time zone, reply_batch boole
id integer NOT NULL DEFAULT nextval('cl_id_seq'::regclass),
from_number character varying(30),
to_number character varying(30),
message text,
received_at timestamp with time zone,
sent_at timestamp with time zone,
reply_batch boolean DEFAULT false,
chat_id character varying(20),
insert_time timestamp with time zone DEFAULT now(),
own_account boolean DEFAULT false,
我有下面的查询,只有当与聊天id相关的insert_time列检查的最后一条消息的own_account列为false时,才会返回会话的聊天id
select chat_id from message_log
where own_account = 'f'
and insert_time in
(
select distinct max(insert_time) from message_log group by chat_id
)
上面的SQL工作得很好,但是它返回对话,而不检查在聊天中own_account列为true的次数。我想添加返回对话聊天ID的功能,这也基于own_帐户的真实次数
我已经尝试了许多不同的SQL查询,但我无法成功地实现这一点。任何帮助都将不胜感激
我希望我足够清楚。如果有任何困惑,请评论
编辑
我已经在这里加载了SQL FIDLE上的数据
如果运行以下查询,它将返回与聊天对话相关的消息
select * from message_log where chat_id = '1412' order by insert_time
最后一条消息不是来自own_帐户,并且结果中的own_帐户消息少于3条,因此下面的查询应该返回它的chat_id,但它不返回
select m.chat_id
from message_log m
inner join
(select chat_id, max(insert_time) as max_insert_time,
count(case when own_account='t' then 1 else 0 end) as true_count
from message_log
group by chat_id) as latest
on m.chat_id = latest.chat_id and
m.insert_time = latest.max_insert_time
where
m.own_account = 'f' and latest.true_count <= 3
编辑2
我在这里用一条记录创建了另一个sql FIDLE
您可以构建一个派生表,记录所有聊天的最新插入时间,然后确定最新记录是否为own_account='f' 扩展它以查找最新的聊天记录为own_account='f',但至少有3个own_account='t'条目的聊天记录
SQLFiddle可在获得感谢您的回答,我在运行两个查询时出现错误,我已在此处粘贴了第二个查询的错误消息。这次没有错误消息,我将在上午检查查询结果,我将接受您的回答。不幸的是,它没有按照我的想法工作,我会给你看一个我编辑过的问题的例子。当你有机会的时候请看一下countcase位应该是sumcase@Gary我将其更改为sum,但我加载了数据库,其中一行包含一条消息,该消息具有own_account false,它不会返回it@Gary我刚刚又加了一个fiddle@gary准确地说,我想我忘了将
select m.chat_id
from message_log m
inner join
(select chat_id, max(insert_time) as max_insert_time
from message_log
group by chat_id) as latest
on m.chat_id = latest.chat_id and
m.insert_time = latest.max_insert_time
where
m.own_account = 'f'
select m.chat_id
from message_log m
inner join
(select chat_id, max(insert_time) as max_insert_time,
sum(case when own_account='t' then 1 else 0 end) as true_count
from message_log
group by chat_id) as latest
on m.chat_id = latest.chat_id and
m.insert_time = latest.max_insert_time
where
m.own_account = 'f' and latest.true_count >= 3