company has_many customers
customer has_many messages
customer belongs_to company
company has_many messages
message belongs_to company
message belongs_to customer
A Message can be "sent" or "received" from the column "direction".
What I would like to find is the number of "conversations" per day where a conversation is defined as a customer sending at least one message and receiving at least one message (doesn't have to be in that order) in a single day, divided by the number of paying companies.
How can I get that in active record?
Complex queries help to narrow a detailed listing obtained as output from an API. To generate the desired output, you can pass queries using And or Or operators in the input XML of an API.
Complex Queries in SQL ( Oracle ) These questions are the most frequently asked in interviews. To fetch ALTERNATE records from a table. ( EVEN NUMBERED) select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);
Message.joins("LEFT JOIN messages AS m ON messages.company_id = m.company_id")
.where("messages.direction = 'sent' AND m.direction = 'received' AND messages.customer_id = m.customer_id AND DATE(messages.created_at) = DATE(m.created_at)")
.select(" DISTINCT (messages.customer_id, messages.company_id, DATE(messages.created_at) )")
.group('Date(messages.created_at)').count
Message.joins("LEFT JOIN messages AS m ON messages.company_id = m.company_id").where("messages.direction = 'sent' AND m.direction = 'received' AND messages.customer_id = m.customer_id AND DATE(messages.created_at) = DATE(m.created_at)").select(" DISTINCT (messages.customer_id, messages.company_id, DATE(messages.created_at) )").group('Date(messages.created_at)').count
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With