2016-08-17 35 views
-2

我有典型的電子商務數據與幾個回頭客,如:如何獲取電子商務數據訂單之間的持續時間?

customer_id, order_date 
1,    2016.05.01 
2,    2016.05.02 
3,    2016.05.03 
1,    2016.05.04 
2,    2016.05.05 
1,    2016.05.06 

而且我想輸出是這樣的:

customer_id,  1,   2,   3, 
1     2016.05.01 2016.05.04 2016.05.06 
1     2016.05.02 2016.05.05 
1     2016.05.03 

,然後我可以輕鬆地獲得第一和第二次購買,等的時間這是在MySQL數據庫中,如果有一個SQL查詢,也很容易

謝謝,千電子伏

+1

你絕對要爲你的問題指定生成數據透視表還是要計算列表中的天的各種命令的數量? SO有很多關於在mysql內部擺動的問題... – Shadow

+0

您打算在單行中返回多少個訂單日期? – shawnt00

+0

我在該結果中看不到任何持續時間 – Strawberry

回答

2

在MySQL中,可能日Ë最簡單的方法是使用變量和條件彙總:

select customer_id, 
     max(case when rn = 1 then order_date end) as order_date_1, 
     max(case when rn = 2 then order_date end) as order_date_2, 
     max(case when rn = 3 then order_date end) as order_date_3 
from (select t.*, 
      (@rn := if(@c = customer_id, @rn + 1, 
         if(@c := customer_id, 1, 1) 
         ) 
      ) as rn 
     from t cross join 
      (select @c := -1, @rn := 1) params 
     order by customer_id, order_date desc 
    ) t 
group by customer_id; 
+0

哇,謝謝!這與我想要的完全一致!非常感謝。該SQL看起來像中國人,但它的作品 – kevando