Attach subqueries of several models with rails

I am trying to write a query below on rails in the simplest and easiest way;

SELECT *
FROM 
    (SELECT DATE(logTime) as Date,
            SUM(CASE WHEN duration/60 <= 2 THEN 1 ELSE 0 END) AS d_0_2,
            SUM(CASE WHEN duration/60 > 2 AND duration/60 <=5 THEN 1 ELSE 0 END) AS d_2_5,
            SUM(CASE WHEN duration/60 > 5 AND duration/60 <= 10 THEN 1 ELSE 0 END) d_5_10,
            SUM(CASE WHEN duration/60 > 10 AND duration/60 <= 15 THEN 1 ELSE 0 END) d_10_15,
            SUM(CASE WHEN duration/60 > 15 THEN 1 ELSE 0 END) d_15_9999
    FROM session_logs
    WHERE DATE(logTime) > "2014-04-1" AND isClosed = 1
    GROUP BY DATE(logTime)) l1
LEFT JOIN
    (SELECT logDate AS Date, potential, conversion, bounce, newCustomers, repeatCustomers, averageTime
    FROM metrics
    WHERE client_id = 1 AND logDate BETWEEN "2014-01-01" AND "2015-05-04"
    GROUP BY logDate) l2 ON l1.date = l2.date

So, I have two models: SessionLog and Metric. I wrote two different queries for each of my models;

metric = Metric.select("potential,conversion,logDate,bounce,newCustomers,repeatCustomers,averageTime").
                where("client_id = ? and logDate between ? and ?",client_id,startDate,endDate)

dwell = SessionLog.select("DATE(logTime) as LogDate,
                                   SUM(CASE WHEN duration/60 <= 2 THEN 1 ELSE 0 END) AS d_0_2, 
                                   SUM(CASE WHEN duration/60 > 2 AND duration/60 <=5 THEN 1 ELSE 0 END) AS d_2_5,
                                   SUM(CASE WHEN duration/60 > 5 AND duration/60 <= 10 THEN 1 ELSE 0 END) d_5_10,
                                   SUM(CASE WHEN duration/60 > 10 AND duration/60 <= 15 THEN 1 ELSE 0 END) d_10_15,
                                   SUM(CASE WHEN duration/60 > 15 THEN 1 ELSE 0 END) d_15_9999").
                            where("client_id = ? AND isClosed = 1 AND DATE(logTime) between ? and ?", client_id, startDate, endDate)

But I could not figure out how to join these date sets.

What would be the best way?

Thank!

+4
source share

All Articles