MySQL - 多个条件

MySQL - multiple conditions

我有两个表:订单,商店。

商店:

shop_id | name 
-----------------------
20      | PizzaShop
34      | SushiShop

订单:

orders_id | creation_time       | user_id | shop_id | Status
------------------------------------------------------------------
1         | 2021-01-01 14:00:00 | 1       | 20      | OK
2         | 2021-02-01 14:00:00 | 1       | 34      | Cancelled
3         | 2021-03-01 14:00:00 | 1       | 20      | OK
4         | 2021-04-01 14:00:00 | 1       | 34      | OK
5         | 2021-05-01 14:00:00 | 2       | 20      | OK
6         | 2021-06-01 14:00:00 | 2       | 20      | OK
7         | 2021-07-01 14:00:00 | 2       | 34      | OK
8         | 2021-08-01 14:00:00 | 2       | 34      | OK

我需要找到每个用户“最喜欢”的商店,知道最喜欢的是“OK”订单多的那家,如果有两家商店的订单量相同,然后 select 有最新订单的那个。

结果应该是这样的:

user_id | total_number_OK_orders | favourite_shop_name 
------------------------------------------------------------------
1       | 3                      | PizzaShop
2       | 4                      | SushiShop

我不知道如何做第二栏。首先,这是我目前拥有的:

SELECT 
    orders.user_id,
    SUM(if(orders.Status = 'OK', 1, 0)) AS total_number_OK_orders
FROM orders
LEFT JOIN shops
    ON orders.shop_id = shops.shop_id
GROUP BY orders.user_id;

对于 MySql 8.0+,您可以使用 window 函数 SUM()FIRST_VALUE():

SELECT DISTINCT o.user_id, 
       SUM(SUM(o.Status = 'OK')) OVER (PARTITION BY o.user_id) total_number_OK_orders,
       FIRST_VALUE(s.name) OVER (PARTITION BY o.user_id ORDER BY SUM(o.Status = 'OK') DESC, MAX(o.creation_time) DESC) favourite_shop_name 
FROM orders o LEFT JOIN shops s
ON s.shop_id = o.shop_id AND o.Status = 'OK'
GROUP BY o.user_id, s.shop_id;

参见demo