简体   繁体   English

mysql 显示表格中的数据最大值和总和

[英]mysql show data max and sum from table

I have two tables and want to display the results for MAX of SUM total, group by name and month.我有两个表,想要显示总和的 MAX 的结果,按名称和月份分组。 only display maximum data from the total SUM results every month and group by name.仅显示每月总 SUM 结果中的最大数据并按名称分组。 this my table这是我的桌子

table t2
+-------+-------+-------+
| month | total | id_t3 |
+-------+-------+-------+
|   1   |  15   |   1   |
|   1   |  20   |   2   |
|   1   |  50   |   1   |
|   2   |  40   |   2   |
|   2   |  20   |   3   |
|   2   |  20   |   1   |
|   3   |  10   |   3   |
+-------+-------+-------+
table t3
+----+--------+
| id |  name  |
+----+--------+
| 1  |  brian |
| 2  |  jessi |
| 3  |  redy  |
+----+---------
i want result 
+-------+---------------+
| month | total |  name |
+-------+---------------+
|   1   |  65   | brian |
|   2   |  40   | jessi |
|   3   |  10   | redy  |
+-------+---------------+

And this my query SQL这是我的查询 SQL

select t2.month, MAX(total), t3.name
from (
select t2.month, SUM(t2.total)as total, t3.name
from t2, t3
where t2.idt3 = t3.id
group by t2.month, t3.name
)result
group by t2.month, t3.name
order by total DESC

Hope it will solve your problem.希望它能解决你的问题。 group by month and name group by

select t2.month, SUM(t2.total), t3.name
from t2
join t3 on t2.id_t3 = t3.id
group by t2.month, t3.name
order by t2.total desc

If you want the maximum name per month, use window functions:如果您想要每月的最大名称,请使用 window 函数:

select month, name, total
from (select t2.month, t3.name, sum(t2.total) as total
             row_number() over (partition by t2.month order by sum(t2.total) desc) as seqnum
      from t2 join
           t3
           on t2.id_t3 = t3.id
      group by t2.month, t3.name
     ) t
where seqnum = 1
order by month;

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

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