sql - Counting columns in a query with group by -


i have following table

  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 time zone,   sent_at timestamp time zone,   reply_batch boolean default false,   chat_id character varying(20),   insert_time timestamp time zone default now(),   own_account boolean default false, 

i have following query return chat_ids of conversations if last message (checked insert_time column) related chat_id has column own_account false.

select chat_id message_log  own_account = 'f' , insert_time in ( select distinct max(insert_time) message_log group chat_id ) 

the above sql works returns conversations without checking how many times own_account column true in chat. add ability return chat_ids of conversations based on how many times own_account true.

i have tried many different sql queries can not succeed @ making work. appreciated.

i hope i'm clear enough. if confused please comment.

edit

i have loaded data on sql fiddle here

http://sqlfiddle.com/#!15/1d7dc/2

if following query ran return messages related chat conversation

select * message_log chat_id = '1412' order insert_time 

the last message not own_account , there less 3 own_account messages in results, following query should return it's chat_id not

select m.chat_id  message_log m inner join    (select chat_id, max(insert_time) max_insert_time,    count(case when own_account='t' 1 else 0 end) true_count    message_log    group chat_id) latest on m.chat_id = latest.chat_id ,    m.insert_time = latest.max_insert_time     m.own_account = 'f' , latest.true_count <= 3 

edit 2

i have created sql fiddle here 1 record

http://sqlfiddle.com/#!15/ad045/1

you can build derived table records latest insert times chats, , find out if latest record own_account='f'

select m.chat_id  message_log m inner join    (select chat_id, max(insert_time) max_insert_time    message_log    group chat_id) latest on m.chat_id = latest.chat_id ,    m.insert_time = latest.max_insert_time     m.own_account = 'f'  

extending find chats latest own_account='f' has @ least 3 own_account='t' entries

select m.chat_id  message_log m inner join    (select chat_id, max(insert_time) max_insert_time,    sum(case when own_account='t' 1 else 0 end) true_count    message_log    group chat_id) latest on m.chat_id = latest.chat_id ,    m.insert_time = latest.max_insert_time     m.own_account = 'f' , latest.true_count >= 3 

sqlfiddle available @ http://sqlfiddle.com/#!15/ee8c0/2


Comments