在按其他两个字段分组时查找最大日期时间 - SQL查询

时间:2017-06-21 00:21:24

标签: sql

第一次在这里发帖。抱歉格式不佳。

我有一个包含订单信息的表格。其中有一个主键OrderID。这是在有人创建购物车时生成的。手头的任务是用相同的电子邮件地址表明之前购买的订单(在这种情况下,假设为60天)。所以基本选择看起来像这样:

SELECT orderid,purchasedate,emailaddress FROM basket

现在 - 棘手的部分是MAX(OrderID),并且购买者并不一定表现出你对他们的期望。也就是说,拥有相同电子邮件地址的人可能会在1月份开始推车,在3月份建立一个新推车,然后购买原始推车。在这种情况下,简单地抓住我的最大订单ID将无法解决问题,因为最大的ID不一定是最近购买的。最终我要寻找的输出应该类似于" CurrentOrderID | EmailAddress | CurrentPurchaseDate | PreviousOrderID | PreviousPurchaseDate"

问题描述有点困难。基本上我试图选择最近购买的BY电子邮件地址,但也包括相应的订单ID。

提前致谢。

2 个答案:

答案 0 :(得分:0)

根据我从上面的描述中理解,我计算下面的子查询(格式因您使用的RDBMS而异,以下是oracle)

select max(orderid) as orderid,purchasedate,emailaddress 
from ( select max(purchasedate) as purchasedate,orderid,emailaddress 
       from market group by orderid,emailaddress ) market_external 
group by purchasedate,emailaddress;

我希望这就是你要找的。

答案 1 :(得分:0)

MySQL 中,下面的查询会将最新的购买记录与所有以后的购买记录一起加入。

SELECT 
    b1.orderId AS currentOrderId,
    b1.emailaddress,
    b1.purchasedate AS currentPurchaseDate, 
    b2.orderId AS previousOrderId,
    b2.purchasedate AS previousPurchaseDate
FROM basket AS b1 
    JOIN basket AS b2 ON(b1.emailaddress = b2.emailaddress AND b1.purchasedate > b2.purchasedate)
ORDER BY b1.emailaddress, b1.purchasedate DESC, b2.purchaseDate DESC 

要查找上一个购买日期最接近当前购买日期的记录,您可以使用MySQL变量创建计数器,并仅选择记录具有排序= 0 。计数器依赖于 ORDER BY b1.emailaddress,b1.purchasedate DESC,b2.purchaseDate DESC 的顺序正常工作。使用其他变量为每封电子邮件重置计数器,以跟踪电子邮件的更改时间。

SELECT 
    b1.orderId AS currentOrderId,
    b1.purchasedate AS currentPurchaseDate, 
    b2.orderId AS previousOrderId,
    b2.purchasedate AS previousPurchaseDate, 
    IF( @previous != b1.emailaddress, @counter:=0, @counter:=@counter+1) AS ordering,
    IF( @previous != b1.emailaddress, @previous:= b1.emailaddress, @previous) AS emailaddress
FROM basket AS b1 
    JOIN basket AS b2 ON(b1.emailaddress = b2.emailaddress AND b1.purchasedate> b2.purchasedate),
    (SELECT @counter:=0, @previous:='') AS tmp
HAVING ordering = 0
ORDER BY b1.emailaddress, b1.purchasedate DESC, b2.purchaseDate DESC