SQL Join 3表并获取最新购买日期

时间:2018-09-13 11:53:59

标签: sql sql-server

我正在寻找客户上次购买的确切日期。

我有一个包含客户信息的表。 我还有一张表格列出了他们在6个月内进行的购买 另一个表格列出了他们购买了6个月以上的商品。

  1. 客户
|customer_id|fname|lname  |
|     1     |John |Doe    |
|     2     |Pete |Jones  |
|     3     |Jane |Evans  |
|     4     |Alan |Malcom |
|     5     |Ron  |Ray    |
  1. 购买历史(在6个月内购买)
|customer_id|product_id|purchase_date      |
|     1     |00001     |2018-02-01 11:35:14|
|     1     |00002     |2018-03-02 12:25:23|
|     3     |00003     |2018-04-03 13:15:34|
|     1     |00001     |2018-05-04 14:45:45|
|     3     |00002     |2018-06-05 15:55:24|
|     2     |00001     |2018-07-01 16:05:41|
  1. PurchaseHistoryArchive(超过6个月的购买)
|customer_id|product_id|purchase_date      |
|     1     |00001     |2017-02-01 11:35:14|
|     1     |00002     |2017-03-02 12:25:23|
|     3     |00003     |2017-04-03 13:15:34|
|     4     |00001     |2017-05-04 14:45:45|
|     3     |00002     |2017-06-05 15:55:24|
|     5     |00001     |2017-07-01 16:05:41|

理想的结果应该是这样的:

|customer_id|fname|lname  |purchase_date      |
|     1     |John |Doe    |2018-05-04 14:45:45|
|     2     |Pete |Jones  |2018-07-01 16:05:41|
|     3     |Jane |Evans  |2018-06-05 15:55:24|
|     4     |Alan |Malcom |2017-05-04 14:45:45|
|     5     |Ron  |Ray    |2017-07-01 16:05:41|

或者,如果不可能,那么可能是这样的:

|customer_id|fname|lname  |purchase_date_new  |purchase_date_old  |
|     1     |John |Doe    |2018-05-04 14:45:45|2017-05-04 14:45:45|
|     2     |Pete |Jones  |2018-07-01 16:05:41|2017-03-02 12:25:23|
|     3     |Jane |Evans  |2018-06-05 15:55:24|2017-06-05 15:55:24|
|     4     |Alan |Malcom |NULL               |2017-05-04 14:45:45|
|     5     |Ron  |Ray    |NULL               |2017-07-01 16:05:41|

我可以使用以下代码针对客户表分别查询PurchaseHistory和PurchaseHistoryArchive表,但理想情况下,我希望在一个查询中进行查询。

SELECT c.customer_id, c.fname, c.lname, p1.purchase_date, p2.purchase_date
FROM customers c
LEFT JOIN purchaseHistory p1 ON (c.customer_id, = p1.customer_id)
LEFT OUTER JOIN purchaseHistory p2 ON (c.customer_id = p2.customer_id AND 
    (p1.purchase_date < p2.purchase_date OR p1.purchase_date = p2.purchase_date AND p1.customer_id < p2.customer_id))
WHERE p2.customer_id IS NULL
ORDER BY customer_id desc;

请问有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以像下面这样编写它,您无需从存档表中提取所有行。

  select p.customer_id, max(p.purchase_date) as last_purchase
  from PurchaseHistory p
  inner join customer c on c.customer_id=p.customer_id
  group by p.customer_id
  union all
  select p.customer_id, max(p.purchase_date) as last_purchase
  from PurchaseHistoryArchive p
  inner join customer c on c.customer_id=p.customer_id
  where not exists(select 1 from PurchaseHistory where customer_id=c.customer_id)
  group by p.customer_id