【问题标题】:find the earliest record找到最早的记录
【发布时间】:2020-11-17 03:06:40
【问题描述】:

我在网上找了很久。但是没有用。请帮助或尝试就如何实现这一目标提出一些想法。那里有 3 个表,我的目标是找到客户第一次购买的月份、星期和客户 ID。客户可能在他们的第一个购物日进行了多次购买,而我希望获得最早的一次。下面是表格和我的尝试。我的代码的问题是它仍然输出重复的客户 ID。我想也许有些顾客在他们的第一个购买日在不同的商店购物。提前致谢。

cust
cust_id  |  first_purchase  |  
001      |   20200107     
002      |   20200109 
003      |   20200102 
004      |   20200103 
date
datetime |  week  |  month |   year
20200107 |   2    |   1    |   2020    |     
20200103 |   1    |   1    |   2020    | 
20200102 |   1    |   1    |   2020    | 
20200101 |   1    |   1    |   2020    |

sale
cust_id  |  store_id  |  time  |   datetime |  
001      |   2342     |  9:00  |   20200107     
002      |   2345     |  8:00  |   20200107     
003      |   6234     |  2:00  |   20200107     
004      |   4533     |  3:00  |   20200107     
Select month, week, cust_id from cust
inner join date on cust. first_purchase= date.datetime
left join 
(select distinct cust_id, store_id,min(datetime),min(time) 
from sale group by cust_id,store_id) 
as bdate 
on cust.cust_id=bdate.cust_id
WHERE year ='2020' and first_purchase IS NOT NULL and MONTH=1 and week=1

【问题讨论】:

  • 你能附上你期望的结果吗

标签: sql rank


【解决方案1】:

嗯。 . .你可以使用row_number():

select s.*, d.*
from (select s.*,
             row_number() over (partition by cust_id order by datetime, time) as seqnum
      from sales s
     ) s join
     date d
     on s.datetime = d.datetime and seqnum = 1;

【讨论】:

  • 感谢您的建议。我试过这种方法。关键问题是我的客户表非常大。如果我只对第一行客户交易进行排序,整个程序可能会花费大量时间。在这种情况下,我试图找到第一个购买日期,然后对时间进行排序
  • @ChLi 。 . .嗯?这不是 SQL 的工作方式。 SQL 查询描述结果集。 SQL 优化器确定最佳执行计划。
最近更新 更多