加入表自己找到一个接一个买的产品

时间:2015-04-05 14:46:57

标签: mysql sql

我有一个包含以下列的表:

+------------------+----------+
| date_of_purchase | product  |
+------------------+----------+
| 2013-06-18       | A        |
| 2013-07-18       | A        |
| 2013-08-24       | A        |
| 2013-10-21       | A        |
| 2013-11-20       | A        |
| 2013-12-20       | A        |
| 2014-01-20       | A        |
| 2014-03-24       | A        |
| 2014-03-24       | B        |
| 2014-04-23       | B        |
| 2014-04-23       | A        |
| 2014-05-16       | B        |
| 2014-05-23       | A        |
+------------------+----------+

我希望得到这样的东西:

+----------+----------+------------+------------+
| product1 | product2 | date_a     | date_b     |
+----------+----------+------------+------------+
| A        | B        | 2014-01-20 | 2014-03-24 |
| A        | B        | 2014-03-24 | 2014-04-23 |
| B        | A        | 2014-05-16 | 2014-05-23 |
| A        | B        | 2014-04-23 | 2014-05-16 |
+----------+----------+------------+------------+

我要做的是检查产品“A”后购买的产品“B”。 我是堆栈溢出的新手,所以我问这个问题的方式可能看起来很模糊。但是需要帮助。

1 个答案:

答案 0 :(得分:0)

派生表使用变量跟踪下一个购买日期,然后使用该变量检查下一个购买日期是否购买了不同的产品

select t1.product, t2.product, t1.date_of_purchase, t2.date_of_purchase from (
    select date_of_purchase, product, 
    @nextDateOfPurchase nextDateOfPurchase,
    @nextDateOfPurchase := date_of_purchase
    from Table1 t
    order by date_of_purchase desc
) t1 join Table1 t2 on t2.date_of_purchase = t1.nextDateOfPurchase
    and t2.product <> t1.product
    and t2.date_of_purchase <> t1.date_of_purchase
order by t1.date_of_purchase

http://sqlfiddle.com/#!9/44b24/3