mysql从表中显示数据最大值和总和
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql从表中显示数据最大值和总和相关的知识,希望对你有一定的参考价值。
我有两张表,想显示SUM总和的MAX结果,按名称和月份分组,只显示每个月SUM总和结果的最大数据,按名称分组。
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 |
+-------+---------------+
这是我的查询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
答案
希望它能解决你的问题。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
另一答案
如果你想要每个月最大的名字,使用窗口功能。
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;
以上是关于mysql从表中显示数据最大值和总和的主要内容,如果未能解决你的问题,请参考以下文章
sql MIN()和MAX()允许您从表中的列中提取最小值和最大值。第1行显示MIN()示例,它选择最小值