2014-11-04 182 views
0

這是我有一個表格,其中包含客戶詳細信息以及他們安裝我的應用程序的時間,即使他們重新安裝了應用程序,他們也會找到返回表格的方式。在下一張表中,我有相同客戶的購買時間。SQL平均複雜查詢

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天隔開購買確切。

回答

-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 
+0

就目前來看,這是一個不好的例子。 請解釋爲什麼你的代碼工作/爲什麼原件不。 – Joshpbarron 2014-11-04 10:30:35

+1

@Joshpbarron沒關係,這是行不通的。 ;-) – Strawberry 2014-11-04 10:35:41

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 | 
+-----+---------+---------------------+---------------------+------+ 

我會離開這個拼圖的最後一塊作爲一個練習留給讀者。