df-drills pandas · Polars · DuckDB SQL · DuckDB Relational 题目列表 登录

组内最大值所在行

中等 10-groupby 分组聚合 groupbyargmaxtiestop-1

找出每个客户金额最大的那一笔订单。

  • 订单金额 amount = 该订单所有订单行的 qty × unit_price 之和(忽略折扣,不区分订单状态)。没有订单行的订单不参与比较。
  • 对每个 customer_id,取 amount 最大的订单;金额并列时取 order_id 较小的那一笔,因此每个客户恰好输出一行。
  • customer_id 为 null 的订单忽略。客户表不参与本题,customer_id 在客户表里查不到的订单照常计算。

输入

  • orders(order_id, customer_id, order_ts, status, channel)
  • order_items(order_id, product_id, qty, unit_price, discount)

输出

列为 customer_id, order_id, amount,行顺序不限。

输入表 (case base,共 2 个 case:base、ties)

orders shop/orders
#order_idint64customer_idint64order_tsdatetimestatusstringchannelstring
1 1001 39 2026-01-01 19:38:00 paid app
2 1002 16 2026-01-17 14:07:00 paid app
3 1003 4 2026-01-08 15:40:20 cancelled web
4 1004 2 2026-05-23 10:48:58 paid null
5 1005 12 2026-06-22 11:07:22 paid store
6 1006 17 2026-08-15 05:15:25 paid web
7 1007 9 2026-06-11 01:00:32 refunded store
8 1008 45 2026-09-19 20:47:10 paid web
9 1009 2 2025-10-05 04:53:38 paid app
10 1010 4 2026-02-19 01:39:54 paid app
11 1011 28 2026-03-05 03:04:45 refunded store
12 1012 2 2026-08-01 07:09:17 paid web
13 1013 26 2026-01-22 03:48:14 refunded store
14 1014 2 2026-02-09 01:41:41 paid app
15 1015 5 2026-08-03 19:49:04 refunded web
16 1016 26 2026-02-16 00:43:43 refunded app
17 1017 9 2025-12-06 04:48:57 pending app
18 1018 999 2026-05-19 12:13:43 paid store
19 1019 26 2026-02-05 15:02:26 paid store
20 1020 44 2025-11-24 11:19:00 cancelled web
显示前 20 行,共 200 行
order_items shop/order_items
#order_idint64product_idint64qtyint64unit_pricefloat64discountfloat64
1 1001 22 3 298.8 null
2 1001 26 1 190.0 0.1
3 1002 6 2 254.2 0.0
4 1002 9 3 79.0 null
5 1002 19 5 305.1 0.2
6 1003 9 2 79.0 0.1
7 1003 28 2 47.4 0.0
8 1004 5 1 500.0 0.1
9 1005 3 1 89.0 0.0
10 1005 12 4 45.0 null
11 1006 13 1 19.9 0.1
12 1006 25 2 39.9 null
13 1007 27 1 12.5 null
14 1008 3 1 89.0 null
15 1008 16 1 29.9 null
16 1008 17 1 129.0 null
17 1009 2 1 49.9 0.0
18 1009 10 2 42.5 null
19 1009 20 1 84.5 0.05
20 1010 1 1 23.8 0.1
显示前 20 行,共 500 行

期望输出 (case base,行顺序不限)

#customer_idInt64order_idInt64amountFloat64
1 3 1185 2792.8
2 6 1044 1331.9
3 38 1079 798.8
4 12 1051 863.2
5 20 1149 650.0
6 36 1064 2009.0
7 998 1089 2109.7
8 4 1010 1073.8
9 24 1035 1152.6
10 40 1137 1002.0
11 43 1078 347.9
12 45 1045 683.9
13 999 1018 328.0
14 1 1022 129.0
15 21 1177 1394.8
16 25 1074 1522.8
17 27 1125 1500.0
18 8 1047 412.0
19 13 1058 145.0
20 19 1090 857.0
21 46 1023 407.0
22 10 1071 300.0
23 18 1070 2142.8
24 29 1105 2807.1
25 34 1117 1814.6
26 47 1198 2128.0
27 49 1077 216.3
28 2 1168 2063.0
29 28 1082 1517.6
30 39 1001 1086.4
31 50 1115 784.4
32 42 1157 2063.8
33 5 1129 1025.5
34 9 1054 647.3
35 14 1036 1130.4
36 17 1161 767.9
37 30 1112 23.9
38 44 1020 259.4
39 35 1042 285.6
40 37 1072 944.8
41 22 1099 1119.7
42 31 1138 1164.9
43 32 1041 416.8
44 11 1087 856.8
45 16 1002 2270.9
46 26 1066 1287.9
共 46 行