使用MySQL中的子查询从一周前减去数据

时间:2014-03-19 20:16:47

标签: mysql sql subquery

我有一些数据,如下所示:

select date_key, count(id) from table1 where date_key between x and y group by date_key;

我想得到一些其他数据如下:

select date_key2, count(id) from table2 where date_key2 between x-7 days and y-7 days group by date_key2;

然后我想分开一个并得到结果。为此,我尝试了:

SELECT t1.date_key,
   I.Converts,
   I.Converts /(SELECT J.Starts FROM (SELECT t2.`date_key`,
      count(id) AS Starts
FROM `table2` t2
WHERE date_key BETWEEN 20140225 AND 20140303
GROUP BY t2.`date_key`)J)
FROM
(
SELECT t1.`date_key`,
      count(id) AS Converts
FROM `table` t1
WHERE date_key BETWEEN 20140304 AND 20140411
GROUP BY t1.`date_key`)I;

我得到“子查询返回超过1行”错误。当我单独运行它们,即选择单独的部件并运行它们时,它们运行良好,但是它们一起崩溃。我究竟做错了什么?

1 个答案:

答案 0 :(得分:1)

要使您的查询正常工作,您可能希望进行加入。基本上分别进行每个分组查询,然后在最后将它们连接在一起。

在下面的查询中,我假设您要计算每日转化率。例如,从第1天开始的用户有资格成为'转换'在第8天。

SELECT I.date_key,
I.Converts,
I.Converts / J.`Starts`
FROM
(
    SELECT t2.`date_key`,
    count(id) AS `Starts`
    FROM `table2` AS t2
    WHERE date_key BETWEEN '2014-02-25' AND '2014-03-03'
    GROUP BY t2.`date_key`
) AS J
JOIN
(
    SELECT t1.`date_key`,
    count(id) AS Converts
    FROM `table` AS t1
    WHERE date_key BETWEEN '2014-03-04' AND '2014-04-11'
    GROUP BY t1.`date_key`
) AS I
ON I.`date_key`=DATE_ADD(J.`date_key`, INTERVAL 7 DAY);

请注意底部应用的日偏移量。这告诉SQL将每个转换日期与7天前的开始日期相连接。