我需要找到预订费用最高的用户,并且如果有2个或更多用户以相同的金额显示所有预订,那么我需要MAX of SUM。
我的餐桌预订缩短了:
import csv
def code_to_names(code):
names = []
with open('offense_codes.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
next(reader) # skip the first row
for row in reader:
names.append(line)
return names
所以我拥有这段代码
reservation_id, user_id, performance_id, amount_to_pay, date
我知道了
SELECT user_id, SUM(amount_to_pay) FROM reservation GROUP BY user_id
它需要向用户1和用户2显示9000。
答案 0 :(得分:0)
一种解决方案是将HAVING
子句与相关子查询一起使用,该子查询获取所有max
之间的sums
值,并将行限制为SUM(amount_to_pay)
等于max_value
。
SELECT
user_id,
SUM(amount_to_pay) AS total
FROM
reservation AS r
GROUP BY
user_id
HAVING
total = (SELECT SUM(amount_to_pay) AS tot
FROM reservation
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
在线示例:DB-Fiddle
对于sum
,只有active
保留,您可以采用以下一种方法:
A)添加对外部查询和子查询的限制:
SELECT
user_id,
SUM(amount_to_pay) AS total
FROM
reservation AS r
WHERE
status = "active"
GROUP BY
user_id
HAVING
total = (SELECT SUM(amount_to_pay) AS tot
FROM reservation
WHERE status = "active"
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
B)在CASE WHEN ... END
方法内使用SUM()
:
SELECT
user_id,
SUM(CASE WHEN status = "active" THEN amount_to_pay END) AS total
FROM
reservation AS r
GROUP BY
user_id
HAVING
total = (SELECT SUM(CASE WHEN status = "active" THEN amount_to_pay END) AS tot
FROM reservation
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
在线示例:DB-Fiddle