簡體   English   中英

如何從派生表中選擇具有 MAX(value) 的行,其中值都是計算的總和?

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

我已經嘗試了以下代碼,但我只是得到了包含所有名稱和總和值的完整表格,而不是具有最大值的一行:

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

但我只需要:搖頭娃娃 11840

PS:請提出一個不使用 desc 和 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

如果有可能出現上領帶,並且您想允許它,您可以使用窗口函數:

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

這是一個適用於任何版本的 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;

在 MySQL 5.7.27 上測試。

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM