使用rails加入多个模型的子查询

时间:2015-04-14 19:55:36

标签: mysql ruby-on-rails rails-activerecord

我正在尝试用最干净,最简单的方式在rails中编写以下查询;

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

所以我有两个模型,SessionLog和Metric。我为每个模型写了两个不同的查询;

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)

但我无法弄清楚我应该如何加入这些日期。

最好的方法是什么?

谢谢!

0 个答案:

没有答案