MySQL-需要找到MAX的SUM查询

时间:2019-01-29 03:05:22

标签: mysql

我需要找到预订费用最高的用户,并且如果有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。

1 个答案:

答案 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