比较同一行

时间:2013-01-29 05:14:53

标签: mysql

我有一个表 - user_tracking - 存储user_id,购买sku和事件time_created。每次用户返回购买时,都会使用新的时间戳引用原始user_id:

User_ID    Sku             Time_Created
  1       1234          2012-10-01 01:00:00
  2       2345          2012-10-02 02:00:00
  3       6789          2012-10-02 01:00:00
  2       5432          2012-10-04 04:00:00

我想衡量回报客户的使用情况,但仅适用于在首次购买后7-60天内退回的客户。目前我的查询类似于:

SELECT
  total_purchases.user_id             as user_1_id,
  total_purchases.time_created        as time_1_created,
  total_purchases.total_purchases     as total_original_purchases,
  total_return.user_id                as user_2_id,
  total_return.time_created           as time_2_created,
  total_return.total_return_purchases as total_return_purchases
FROM (SELECT
    user_tracking.user_id                as user_id,
    user_tracking.time_created           as time_created,
    COUNT(DISTINCT user_tracking.sku)    as total_purchases
      FROM user_tracking
      WHERE user_tracking.time_created BETWEEN "2012-10-01 00:00:00"
      AND "2012-10-15 00:00:00") AS total_purchases
  LEFT JOIN (SELECT
           user_tracking.user_id                as user_id,
           user_tracking.time_created           as time_created,
           COUNT(DISTINCT user_tracking.sku)    as total_return_purchases
         FROM user_tracking
         WHERE user_tracking.time_created BETWEEN "2012-10-01 00:00:00"
         and "2012-12-15 00:00:00") AS total_return
    ON total_purchases.user_id = total_return.user_id

如何确保我只在原始用户的7-60天内测量购买?

1 个答案:

答案 0 :(得分:0)

您可以使用间隔

AND datecolumn BETWEEN (datecolumn, INTERVAL 7 DAYS) AND (datecolumn, INTERVAL 60 DAYS)