按客户选择最近订购的最昂贵产品的名称

时间:2020-08-07 08:28:08

标签: mysql sql join aggregate-functions

我有2张桌子:

  • 包含order_id,order_date,customer_id,product_id,收入的订单
  • 包含product_id和product_name的产品

我想做的是按客户选择他最近订购的最昂贵产品的名称

SELECT MAX(o.ORDER_DATE), MAX(o.REVENUE) , PRODUCT_NAME
FROM orders o 
JOIN products p ON o.PRODUCT_ID = p.PRODUCT_ID
GROUP BY CUSTOMER_ID, ORDER_ID, PRODUCT_NAME

2 个答案:

答案 0 :(得分:0)

SELECT DISTINCT
       MAX(o.order_date) OVER (PARTITION BY customer_id) order_date, 
       FIRST_VALUE(o.revenue) OVER (PARTITION BY customer_id 
                                    ORDER BY order_date DESC, revenue DESC) revenue, 
       FIRST_VALUE(product_name) OVER (PARTITION BY customer_id 
                                       ORDER BY order_date DESC, revenue DESC) product_name       
FROM orders o 
JOIN products p USING (product_id)

答案 1 :(得分:0)

您所说的数据模型没有有关“最昂贵产品”的信息。让我假设products实际上有一个列,例如“ price”。

我想建议窗口功能:

SELECT op.*
FROM (SELECT o.*, p.*
             ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.order_date DESC, p.price DESC) as seqnum
      FROM orders o JOIN
           products p
           ON o.PRODUCT_ID = p.PRODUCT_ID
     ) op
WHERE seqnum = 1;

每个客户返回一行。如果存在平局,并且想要所有行,请将ROW_NUMBER()更改为RANK()。请注意,此方法为您提供了很大的灵活性,可以在结果集中包括哪些列。