SQL平均复杂查询

时间:2014-11-04 09:30:04

标签: mysql sql database code-analyst

这是我有一个表格,其中包含客户详细信息以及安装我的应用程序的时间,即使他们重新安装了应用程序,他们也会找到回到表格的方式。在下表中,我有相同客户的购买时间。

users
uid Version install_time
1   1   2013-06-01 00:00:00
1   2   2014-06-01 00:00:00  
1   3   2014-10-01 00:00:00
2   3   2014-11-11 00:00:00
3   2   2013-11-11 00:00:00
4   4   2015-01-01 00:00:00

trans
uid transaction_time
1   2013-07-01 00:00:00
1   2014-07-01 00:00:00
1   2014-11-01 00:00:00
2   2014-12-11 00:00:00
999 2014-11-04 00:13:49

问:平均而言,客户第一次购买需要多少天?

这是我到目前为止所尝试的:

select avg(`purchase after install`) as average
from 
(
select 
u.uid,
dayofyear(t.transaction_time)-dayofyear(u.install_time) AS `purchase after install`
from users u 
left join trans t -- joining the transaction time to user table 
on u.uid=t.uid
where t.transaction_time >= u.install_time -- because the cartesian product from the join is creating additional rows for uid 1
-- group by 1
) final

我有65天的时间,但是如果你注意到这张桌子的平均值应该是30天,因为我的购买时间间隔为30天。

2 个答案:

答案 0 :(得分:0)

 DROP TABLE IF EXISTS users;

 CREATE TABLE users
 (uid INT NOT NULL
 ,Version INT NOT NULL
 ,install_time DATETIME NOT NULL
 ,PRIMARY KEY(uid,Version,install_time)
 );

 INSERT INTO users VALUES
 (1   ,1   ,'2013-06-01 00:00:00'),
 (1   ,2   ,'2014-06-01 00:00:00'),
 (1   ,3   ,'2014-10-01 00:00:00'),
 (2   ,3   ,'2014-11-11 00:00:00'),
 (3   ,2   ,'2013-11-11 00:00:00'),
 (4   ,4   ,'2015-01-01 00:00:00');

 DROP TABLE IF EXISTS trans;

 CREATE TABLE trans
 (uid INT NOT NULL
 ,transaction_time DATETIME NOT NULL
 ,PRIMARY KEY(uid,transaction_time)
 );

 INSERT INTO trans VALUES
 (1   ,'2013-07-01 00:00:00'),
 (1   ,'2014-07-01 00:00:00'),
 (1   ,'2014-11-01 00:00:00'),
 (2   ,'2014-12-11 00:00:00'),
 (999 ,'2014-11-04 00:13:49');

 SELECT u.*
      , MIN(t.transaction_time) min_t
      , DATEDIFF(MIN(t.transaction_time),u.install_time) diff 
   FROM users u 
   JOIN trans t 
     ON t.uid = u.uid 
    AND t.transaction_time >= u.install_time 
  GROUP 
     BY u.uid
      , u.version
      , u.install_time;
 +-----+---------+---------------------+---------------------+------+
 | uid | Version | install_time        | min_t               | diff |
 +-----+---------+---------------------+---------------------+------+
 |   1 |       1 | 2013-06-01 00:00:00 | 2013-07-01 00:00:00 |   30 |
 |   1 |       2 | 2014-06-01 00:00:00 | 2014-07-01 00:00:00 |   30 |
 |   1 |       3 | 2014-10-01 00:00:00 | 2014-11-01 00:00:00 |   31 |
 |   2 |       3 | 2014-11-11 00:00:00 | 2014-12-11 00:00:00 |   30 |
 +-----+---------+---------------------+---------------------+------+

我将这个谜题的最后一部分作为读者的练习。

答案 1 :(得分:-1)

尝试

select AVG(datediff(day,a.date1,b.date2)) from  table1 as a inner join table2 as b on a.id=b.id where a.date1>=b.date2