简体   繁体   English

如何从派生表中选择具有 MAX(value) 的行,其中值都是计算的总和?

[英]How can I SELECT a row with MAX(value) from a derived table where the values are all calculated sums?

I have tried the following code but I just get the full table with all the names and sum values instead of one row with the max value:我已经尝试了以下代码,但我只是得到了包含所有名称和总和值的完整表格,而不是具有最大值的一行:

SELECT stageName, max(total_salary)
FROM (
      SELECT c.*, sum(p.dailySalary) as total_salary        
      from contender as c
      left join participant as p
      on (p.contender = c.idContender)
      group by c.idContender ) b
group by stageName;
output: 
Yellow Jesters  205
TikTok  3073
Teabags 947
Bobbleheads 11840
Reddit  1486

but I just need: Bobbleheads 11840但我只需要:摇头娃娃 11840

PS: Please suggest a solution WITHOUT using desc and limit PS:请提出一个不使用 desc 和 limit 的解决方案

If you just want to top row in your resultset, you can sort and limit:如果您只想在结果集中排在第一行,您可以排序和限制:

select c.*, sum(p.dailySalary) as total_salary        
from contender as c
left join participant as p on p.contender = c.idContender
group by c.idContender
order by total_salary desc
limit 1

If there is a possibility of top tie, and you want to allow it, you can use window functions:如果有可能出现上领带,并且您想允许它,您可以使用窗口函数:

select *
from (
    select 
        c.*, 
        sum(p.dailySalary) as total_salary, 
        rank() over(order by sum(p.dailySalary) desc) rn
    from contender as c
    left join participant as p on p.contender = c.idContender
    group by c.idContender
) t
where rn = 1

Here's a solution that should work on any version of MySQL 5.x, using no ORDER BY, LIMIT, window functions, views, or CTEs.这是一个适用于任何版本的 MySQL 5.x 的解决方案,不使用 ORDER BY、LIMIT、窗口函数、视图或 CTE。

SELECT a.stagename, a.total_salary
FROM (
      SELECT c.*, sum(p.dailySalary) as total_salary        
      from contender as c
      left join participant as p
      on (p.contender = c.idContender)
      group by c.idContender ) AS a
LEFT OUTER JOIN (
      SELECT c.*, sum(p.dailySalary) as total_salary        
      from contender as c
      left join participant as p
      on (p.contender = c.idContender)
      group by c.idContender ) AS b
  ON a.total_salary < b.total_salary
WHERE b.total_salary IS NULL;

Tested on MySQL 5.7.27.在 MySQL 5.7.27 上测试。

Output:输出:

+-------------+--------------+
| stagename   | total_salary |
+-------------+--------------+
| Bobbleheads |        11840 |
+-------------+--------------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM