company has_many customers
customer has_many messages
customer belongs_to company
company has_many messages
message belongs_to company
message belongs_to customer
可以发送消息"或者"收到"从列"方向"。
我想要找到的是#34;对话的数量"每天,对话被定义为客户发送至少一条消息并在一天内接收至少一条消息(不必按此顺序),除以付费公司的数量。
如何在活动记录中获得该信息?
答案 0 :(得分:8)
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