Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get this complex query?

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?

like image 692
Matthew Berman Avatar asked Dec 08 '14 20:12

Matthew Berman


People also ask

What is complex query?

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.

What is complex query in SQL with example?

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);


1 Answers

Lets split the query into parts:

1. You need to join the message table on itself on same company id.

Message.joins("LEFT JOIN messages AS m ON messages.company_id = m.company_id")

2. Where customer is same for the two joined messages where messages is sent and m is received on the same day

.where("messages.direction = 'sent' AND m.direction = 'received' AND messages.customer_id = m.customer_id AND DATE(messages.created_at) = DATE(m.created_at)")

3. You need to get the uniq messages sent and received by every customer everyday to/from the same company.

.select(" DISTINCT (messages.customer_id, messages.company_id, DATE(messages.created_at) )")

4. Count Grouping by date created

.group('Date(messages.created_at)').count

Final Query:

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
like image 120
mohameddiaa27 Avatar answered Oct 23 '22 22:10

mohameddiaa27